- A+
所属分类:.NET技术
简介:
问题:在WPF中,使用了ObservableCollection<T>作为dataGrid的数据源,发现更新数据的时候不会触发dataGrid的更新
By MaQaQ 2023-11-22
分析:
1、ObservableCollection 会在集合的元素添加、移除或者清空时才触发更新通知,对集合中元素的属性更改是不会触发通知的。
2、如果想在更新数据时触发通知,可以将 T类实现 INotifyPropertyChanged 接口,这样当其属性发生更改时,会触发通知并更新 dataGrid。
实现如下:
1、xml中
<DataGrid x:Name="dataGrid" ItemsSource="{Binding}" >
2、cs中
- 定义ObservableCollection<Model> memberData = new ObservableCollection<Model>();
- Model定义如下:
public class Model : INotifyPropertyChanged { protected int id; protected string name; protected bool online; protected bool registered; public int ID { get => id; set => id = value; } public string Name { get => name; set => name = value; } public bool IsOnline { get => online; set { if (online != value) { online = value; OnPropertyChanged("IsOnline"); } } } public bool IsRegistered { get => registered; set { if (registered != value) { registered = value; OnPropertyChanged("IsRegistered"); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }
View Code
- 绑定dataGrid数据源:dataGrid.DataContext = memberData;
- 更新memberData数据:
private void ElevatorChanged(Data.ElevatorModel model) { var result1 = memberData.Count == 0 ? null : memberData.Where(p => p.Name == model.Name).Count() == 0 ? null : memberData.Where(p => p.Name == model.Name).First(); if (result1 != null) { result1.ID = model.ID; result1.Name = model.Name; result1.IsOnline = model.IsOnline; result1.IsRegistered = model.IsRegistered; } else { memberData.Add(model); } }
View Code
上述例子中,当IsOnline、IsRegistered更新或者memberData.Add(model)时,会触发通知并更新dataGrid的显示。
总结:
1、使用ObservableCollection会在集合的元素添加、移除或者清空时才触发更新
2、使用INotifyPropertyChanged 接口会在属性发生更改时触发通知