您注释为的位置// 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();
}