赋值后TextBlock未即时更新问题求助(WPF DataGrid场景)
问题分析与解决方案
核心问题是你的itemAsm类没有实现INotifyPropertyChanged接口,WPF的数据绑定依赖这个接口的PropertyChanged事件来通知UI更新属性值变化。直接修改Selected.destLocCol时,UI无法感知属性变更,只有双击触发UI重新绑定(比如进入编辑模式再退出)才会显示新值。
具体修改步骤
1. 让itemAsm类实现INotifyPropertyChanged接口
修改itemAsm类,添加接口实现与属性变更通知逻辑:
using System.ComponentModel; using System.Runtime.CompilerServices; public class itemAsm : INotifyPropertyChanged { private string _prefCol; private string _fileLocCol; private string _suffCol; private string _destLocCol; public string prefCol { get => _prefCol; set { _prefCol = value; OnPropertyChanged(); } } public string fileLocCol { get => _fileLocCol; set { _fileLocCol = value; OnPropertyChanged(); } } public string suffCol { get => _suffCol; set { _suffCol = value; OnPropertyChanged(); } } public string destLocCol { get => _destLocCol; set { _destLocCol = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. 额外优化建议
如果后续需要通过代码修改Selected属性来更新UI,窗口类也需要实现INotifyPropertyChanged接口,并给Selected添加变更通知:
using System.ComponentModel; using System.Runtime.CompilerServices; public partial class unitCopierFrm : Window, INotifyPropertyChanged { private itemAsm _selected; public itemAsm Selected { get => _selected; set { _selected = value; OnPropertyChanged(); } } public ObservableCollection<itemAsm> SelectedAsm { get; set; } public unitCopierFrm() { InitializeComponent(); SelectedAsm = new ObservableCollection<itemAsm>(); DataContext = this; } // 省略原有按钮点击事件代码... public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者ZeroPanda
相关产品推荐
相关产品推荐

