I am confused about how ObservableCollection and INotifyPropertyChanged works.
I have this code:
Payments = new ObservableCollection<PaymentViewModel>(_allPayments);
public ObservableCollection<PaymentViewModel> Payments
{
get { return _payments; }
set {
_payments = value;
RaisePropertyChanged("Payments");
}
}
I don’t understand what is the relationship between ObservableCollection and INotifyPropertyChanged here. Can you explain?
ObservableCollectionis a specialized collection that can notify subscribers when its contents change, whileINotifyPropertyChangedis an interface that allows implementors 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 setter in your example).
Consider this code:
Subscribers to the
INotifyCollectionChanged.CollectionChangedevent would now know that things have changed and they should update accordingly.But now look at this:
After adding an item to the collection we then swap the entire collection for another one. If an
ItemsControlis bound to this collection we expect it to update itself and reflect the fact thatmodel.Paymentsends up being empty. But how can it do that?CollectionChangedwill not help because the original collection (after receiving its first item) was not modified; we just discarded it and installed another in its place. The only one who knows that the switch happened is thePaymentsproperty setter. So the setter utilizesINotifyPropertyChangedto tell subscribers that the collection has been replaced with another, and they should of course update their status.Conclusion: Data binding works automagically in WPF because all the databound controls listen to the
INotifyPropertyChangedof theirDataContext, and if the binding target implementsINotifyCollectionChangedthey subscribe to that as well. If the binding target changes they are notified throughINotifyPropertyChanged, unsubscribe fromINotifyCollectionChangedon the old target and subscribe to it on the new one.