List<> collection does not update the View in M

2019-02-19 12:57发布

I used the List<Person> collection as the ItemsSource for the DataGrid control.

But it did not update the View if i remove the item from the List collection. I was struggling for a long time for the solution.

Then Instead of the List<Person> collection in my ViewModel. I changed this into ObservableCollection<Person> collection. Now it updates the view when ever there is a change in the collection.

I am not sure why it updates only for ObservableCollection<Person> ? Anyone ?

标签: wpf mvvm
4条回答
smile是对你的礼貌
2楼-- · 2019-02-19 13:21

Because List does not implement INotifyCollectionChanged

查看更多
爷、活的狠高调
3楼-- · 2019-02-19 13:25

ObservableCollection<T> fires change events every time you change the items in the collection. List<T> doesn't. That's the reason.

DataBinding is lazy. If you don't tell your view that something has changed, it won't bother updating. Under the hoods, WPF DataBinding registers for change notifications, so that your ViewModel can tell the view when it has changed. It does this with interfaces like INotifyPropertyChanged and INotifyCollectionChanged.

ObservableCollection<T> implements the interface INotifyCollectionChanged. This interface defines the event CollectionChanged, which your View basically attaches its own event handler to. That handler will update the view when the event is raised by the collection.

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-19 13:30

Well its in the name. A simple List doesn't tell the ui to update, in other words "the view can't observe the list". There is no weird magic behind Databinding. WPF and DataBinding needs the Data model to tell them "this is new" or "this is changed", you propably already saw INotifyPropertyChanged, INotifyCollectionChanged is the same but for collections, and the List<> doesn't implement it, ObservableCollection does.

查看更多
成全新的幸福
5楼-- · 2019-02-19 13:39

Because the update of a databinding is not a kind of magic, there are several requirements to make databinding working correctly. If you have a single property to bind on this property must be either a dependency property or its parent class must implement the INotifyPropertyChanged interface to notify the wpf binding system about changes of the property value. For a collection there is a simelar mechanism: it must implement INotifyPropertyChanged to inform the wpf binding system about removed/moved/added items.

See here for more details: http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx

查看更多
登录 后发表回答