When using ObservableCollection<T>, do I still need to implement INotifyPropertyChanged on type T?

做~自己de王妃 提交于 2020-01-12 15:48:14

问题


The MSDN reference page for ObservableCollection<T> notes:

"The objects in your collection must satisfy the requirements described in the Binding Sources Overview. In particular, if you are using OneWay or TwoWay (for example, you want your UI to update when the source properties change dynamically), you must implement a suitable property changed notification mechanism such as the INotifyPropertyChanged interface."

Since ObservableCollection<T> already implements INotifyPropertyChanged, why do I need to again implement INotifyPropertyChanged on T also?


回答1:


Consider your observable collection as a data source for a table. Each object from the collection occupies one row, and is displayed in the table across multiple columns.

The view (i.e. your table) needs to know when to modify each cell in response to changing properties of objects, but also in response to adding and removing objects to and from the collection.

Your observable collection takes care of dealing with table rows: it notifies its observers when an object gets inserted, removed, moved, and so on. However, it lacks knowledge of what's going on with individual objects, so it is of no help in dealing with table columns.

This is where your objects come in: by implementing INotifyPropertyChanged they let your table manage the data in the columns.




回答2:


INotifyPropertyChanged needs to be raised by the object whose properties are changing. ObservableCollection cannot simply detect changes in the objects it contains and pass those along on your behalf.

The reason the collection implements INotifyPropertyChanged isn't particularly useful. I suspect it is only going to raise a change event for the Count property of the collection which would change as items are added/removed to the collection.

If you are only interested in items being added/removed, you may not need to implement this interface in your class. But if your UI is binding to properties of the object, you'll need to implement it if you want the UI to react.



来源:https://stackoverflow.com/questions/10291339/when-using-observablecollectiont-do-i-still-need-to-implement-inotifyproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!