您注释为的位置
// Code to trig on item change...仅在更改集合对象(例如将其设置为新对象或设置为null)时触发。
根据您目前的实现TrulyObservableCollection的,处理您的收藏的属性更改事件,注册一些东西到
CollectionChanged的事件
MyItemsSource
public MyViewModel(){ MyItemsSource = new TrulyObservableCollection<MyType>(); MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged; MyItemsSource.Add(new MyType() { MyProperty = false }); MyItemsSource.Add(new MyType() { MyProperty = true}); MyItemsSource.Add(new MyType() { MyProperty = false });}void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){ // Handle here}我个人真的不喜欢这种实现。您正在引发一个
CollectionChanged事件,该事件表明在属性更改时,整个集合已被重置。当然,只要集合中的某个项目发生更改,它就可以使UI随时更新,但是我发现这样做对性能不利,而且似乎没有办法确定更改了哪些属性,这是关键信息之一做某事时我通常需要
PropertyChanged。
我更喜欢使用常规方法,
ObservableCollection而只是将
PropertyChanged事件关联到上的项目
CollectionChanged。如果您的UI已正确绑定到中的项目,则
ObservableCollection当集合中某个项目的属性发生更改时,您无需告诉UI进行更新。
public MyViewModel(){ MyItemsSource = new ObservableCollection<MyType>(); MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged; MyItemsSource.Add(new MyType() { MyProperty = false }); MyItemsSource.Add(new MyType() { MyProperty = true}); MyItemsSource.Add(new MyType() { MyProperty = false });}void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){ if (e.NewItems != null) foreach(MyType item in e.NewItems) item.PropertyChanged += MyType_PropertyChanged; if (e.OldItems != null) foreach(MyType item in e.OldItems) item.PropertyChanged -= MyType_PropertyChanged;}void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e){ if (e.PropertyName == "MyProperty") DoWork();}


