ObservableCollection 和 BindingList 的区别 [英] Difference between ObservableCollection and BindingList
问题描述
我想知道 ObservableCollection
和 BindingList
之间的区别,因为我已经使用两者来通知 Source 中的任何添加/删除更改,但我实际上不知道什么时候更喜欢一个.
I want to know the difference between ObservableCollection
and BindingList
because I've used both to notify for any add/delete change in Source, but I actually do not know when to prefer one over the other.
为什么我会选择以下其中之一?
Why would I choose one of the following over the other?
ObservableCollection<Employee> lstEmp = new ObservableCollection<Employee>();
或
BindingList<Employee> lstEmp = new BindingList<Employee>();
推荐答案
ObservableCollection
可以像任何集合一样从 UI 更新.真正的区别相当简单:
An ObservableCollection
can be updated from UI exactly like any collection. The true difference is rather straightforward:
ObservableCollection
实现了 INotifyCollectionChanged
,它在集合更改时提供通知(你猜对了 ^^)它允许绑定引擎在 ObservableCollection
更新时更新 UI.
ObservableCollection<T>
implements INotifyCollectionChanged
which provides notification when the collection is changed (you guessed ^^)
It allows the binding engine to update the UI when the ObservableCollection
is updated.
然而,BindingList
实现了 IBindingList
.
IBindingList
提供有关集合更改的通知,但不仅如此.它提供了一大堆功能,用户界面可以使用这些功能来提供更多的东西,而不仅仅是根据变化更新用户界面,例如:
IBindingList
provides notification on collection changes, but not only that. It provides a whole bunch of functionality which can be used by the UI to provide a lot more things than only UI updates according to changes, like:
- 排序
- 正在搜索
- 通过工厂添加(AddNew 成员函数).
- 只读列表(CanEdit 属性)
所有这些功能在 ObservableCollection
另一个区别是 BindingList
在其项目实现 INotifyPropertyChanged
时中继项目更改通知.如果一个项目引发一个 PropertyChanged
事件,BindingList
将接收它并引发一个带有 ListChangedType.ItemChanged
的 ListChangedEvent
和OldIndex=NewIndex
(如果一个项目被替换,OldIndex=-1
).ObservableCollection
不中继项目通知.
Another difference is that BindingList
relays item change notifications when its items implement INotifyPropertyChanged
. If an item raises a PropertyChanged
event, the BindingList
will receive it an raises a ListChangedEvent
with ListChangedType.ItemChanged
and OldIndex=NewIndex
(if an item was replaced, OldIndex=-1
). ObservableCollection
doesn't relay item notifications.
请注意,在 Silverlight 中,BindingList
不可用作选项:但是,您可以使用 ObservableCollection
s 和 ICollectionView
(和 如果我没记错的话,IPagedCollectionView
).
Note that in Silverlight, BindingList
is not available as an option: You can however use ObservableCollection
s and ICollectionView
(and IPagedCollectionView
if I remember well).
这篇关于ObservableCollection 和 BindingList 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!