ObservableCollection
is a specialized collection that can notify subscribers when its contents change, and INotifyPropertyChanged
is an interface that allows developers to notify subscribers when one of their properties changes value.
You are probably wondering how the two are related (because both are involved in the installer in your example).
Consider this code:
var model = new MyViewModel();
Subscribers of INotifyCollectionChanged.CollectionChanged
will now know that everything has changed and they should update accordingly.
But look at this:
var model = new MyViewModel();
After adding an item to the collection, we will replace the entire collection with another. If the ItemsControl
tied to this collection, we expect it to update itself and reflect the fact that model.Payments
ends up empty. But how can this be done?
CollectionChanged
will not help, because the original collection (after receiving its first element) has not been changed; we just dropped it and set another in its place. The only one who knows that this is a switch is setterter Payments
. Therefore, the setter uses INotifyPropertyChanged
to inform subscribers that the collection has been replaced by another, and they must, of course, update their status.
Conclusion: Data binding works automatically in WPF because all data controls support INotifyPropertyChanged
their DataContext
, and if the binding target implements INotifyCollectionChanged
, they also subscribe to it. If the binding target changes, they are notified through INotifyPropertyChanged
, unsubscribed from INotifyCollectionChanged
by the old target and subscribe to it on a new one.
source share