Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 216
rajibdotnet Avatar asked Apr 24 '12 03:04

rajibdotnet


2 Answers

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.

like image 152
Sergey Kalinichenko Avatar answered Sep 28 '22 08:09

Sergey Kalinichenko


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.

like image 28
Josh Avatar answered Sep 28 '22 06:09

Josh