ObservableCollection引发“Item[]”的PropertyChange的目的是什么?
如果我有一个实现了INotifyCollectionChanged的类,这是我应该做的吗?
WPF控件是否以某种方式使用“Item[]”的PropertyChange?
ObservableCollection
实现了INotifyCollectionChanged
和INotifyPropertyChanged
接口。
INotifyPropertyChanged
用于指示ObservableCollection
的属性已更改,例如其元素数量("Count"
)或通过集合索引器("Item[]"
)访问的元素。此外,ObservableCollection
还实现了INotifyCollectionChanged
接口,以指示哪个元素已经更改以及如何更改。
请查看Mono中ObservableCollection
的实现,以了解ObservableCollection
的确切功能。例如,这里是InsertItem
方法的实现:
protected override void InsertItem (int index, T item)
{
CheckReentrancy ();
base.InsertItem (index, item);
OnCollectionChanged (new NotifyCollectionChangedEventArgs (
NotifyCollectionChangedAction.Add, item, index));
OnPropertyChanged (new PropertyChangedEventArgs ("Count"));
OnPropertyChanged (new PropertyChangedEventArgs ("Item[]"));
}
如果您想要实现自己的类似于ObservableCollection
的集合类,那么实现INotifyCollectionChanged
和INotifyPropertyChanged
似乎是正确的方式。
是的,WPF和Silverlight控件使用PropertyChange事件来更新UI控件。这使得像ListView或DataGrid这样的控件能够自动响应它们绑定的ObservableCollection - 或其他实现了INotifyCollectionChanged的集合 - 的更改而更新。
编辑:就实现而言,您通常不需要实现自己的集合,因此不需要担心INotifyCollectionChanged。对于将在ObservableCollection中使用的类,您需要实现INotifyPropertyChanged。这允许您的对象在更新时触发PropertyChanged事件,从而使您的UI控件自动显示更改。