What is the difference between ObservableCollection and INotifyPropertyChanged?

I am confused about how ObservableCollection and INotifyPropertyChanged .

I have this code:

 Payments = new ObservableCollection<PaymentViewModel>(_allPayments); public ObservableCollection<PaymentViewModel> Payments { get { return _payments; } set { _payments = value; RaisePropertyChanged("Payments"); } } 

I do not understand what is the relationship between ObservableCollection and INotifyPropertyChanged here. Can you explain?

+6
source share
2 answers

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(); // assume it the class with Payments inside model.Payments.Add(new PaymentViewModel()); 

Subscribers of INotifyCollectionChanged.CollectionChanged will now know that everything has changed and they should update accordingly.

But look at this:

 var model = new MyViewModel(); // assume it the class with Payments inside model.Payments.Add(new PaymentViewModel()); // OK, we know what this does model.Payments = new ObservableCollection<PaymentViewModel>(); 

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.

+6
source

ObservableCollection notifies its binder, for example, when something is added / removed in the collection itself.

What you do in the second example, however, notifies the binder that the collection has been replaced with a new collection (something that the ObservableCollection does not do itself, if you make a new ObservableCollection - there you lose the binding).

+2
source

Source: https://habr.com/ru/post/913727/


All Articles