wpf - 针对 INotifyCollectionChanged 类型的数据绑定(bind)

标签 wpf mvvm inotifycollectionchanged

我想要一个域模型集合类和一个 View 模型类,它只反射(reflect)和投影域模型的元素 - 但本身是只读的。

我的想法是,这两种类型都实现了 INotifyCollectionChanged 接口(interface),而 View 模型类型则充当代理和投影仪,将模型元素包装在元素 View 模型类型中。

问题是:实现 INotifyCollectionChanged 是否足以使 WPF 数据绑定(bind)到例如DataGrid 或 ListView 或者启用基于集合的数据绑定(bind)所需的最小接口(interface)集是什么?

最佳答案

如果集合中元素内的属性发生更改,INotifyCollectionChanged 不会更新您的 UI,除非在集合中添加或删除整个元素。

因此,如果您愿意跟踪整个元素更改,那么 INotifyCollectionChanged 就足够了,任何进一步的粒度,您都需要在属性 setter 中实现 INotifyPropertyChanged .

另一点值得注意的是,如果您使用 ObservableCollection 来容纳您的列表,那么它已经为您实现了 INotifiyCollectionChanged

编辑:

以下是 Microsoft 的观点;

You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes an event that should be raised whenever the underlying collection changes.

WPF provides the ObservableCollection(Of T) class, which is a built-in implementation of a data collection that exposes the INotifyCollectionChanged interface.

Note that to fully support transferring data values from source objects to targets, each object in your collection that supports bindable properties must also implement the INotifyPropertyChanged interface.

Before implementing your own collection, consider using ObservableCollection(Of T) or one of the existing collection classes, such as List(Of T), Collection(Of T), and BindingList(Of T), among many others. If you have an advanced scenario and want to implement your own collection, consider using IList, which provides a non-generic collection of objects that can be individually accessed by index and thus the best performance.

来自..

http://msdn.microsoft.com/en-us/library/ms752347.aspx#binding_to_collections

关于wpf - 针对 INotifyCollectionChanged 类型的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15260240/

相关文章:

wpf - 有没有更好的方法在 WPF 中继承窗口

wpf - 选择更改时 DataGridComboBoxColumn 丢失其内容

.net - Dragablz 组件并使用不同的窗口作为宿主

c# - EntityFramework EntityCollection 观察 CollectionChanged

c# - DataGridView 和 INotifyCollectionChanged

Wpf - 相对图像源路径

wpf - 从 XAML 指向 View 中的 ModelView

silverlight - 在Silverlight中拦截ViewModel

silverlight - MVVM : how to pass parameter to ViewModel's constructor

wpf - 可观察链表