问题
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