9

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?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
rajibdotnet
  • 1,498
  • 2
  • 17
  • 29

2 Answers2

10

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • That's related to notifying about the changes in the collection content (items can be added, updated and removed). What about notifying of the collection container changes? The property the view is bound to, of type ObservableCollection has also to be assigned and can be changed. I assume INPC must be implemented in the setter for this property (unless it is a dependency property), but many code excerpts don't show this implementation. Correct? [This answer](https://stackoverflow.com/a/30774557/774575) says is it, but had 0 votes before I saw it. – mins Aug 18 '20 at 17:59
3

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.

Josh
  • 68,005
  • 14
  • 144
  • 156