How to implement INotifyPropertyChanged and observ

2019-07-10 15:48发布

问题:

I have an ObservableCollection of Products in the Model, and I want the ViewModel to listen to any changes in the ObservableCollection of Products.

Im not sure about how to go and implement it. Ive read several tutorials, but most of them are not MVVM specific.

Should i implement the INotifyPropertyChanged in the ViewModel class, how do I specify that i want to listen to the OberserableCollection of Products?

Thanks :)

回答1:

I know this has already been answered, but there is more to consider.

1) a ViewModel should implement INotifyPropertyChanged, that's one of the things that makes it a ViewModel. Even in the unlikely case that the only property it exposes is the ObservableCollection, it will need to raise property changed when the actual ObservableColelction property is changed (more on this in item 3)

2) do you really want the ViewModel to listen for these changes or the View? Those are two different things. The ViewModel should hold an ObservableCollection which is then bound to the View. What you want is for the View to react to those changes. In that case, Brandon is correct that ObservableCollection does this for you out of the box. So the View has an instance of the ViewModel set as a DataContext and some visual element in your View is bound to the ObservableCollection (like an ItemsSource on a ListBox).

3) the exception is the ObservableCollection property itself in the ViewModel. While ObservableCollection implements INotifyPropertyChanged, that is part of the collection object: when that object reference changes (like it is recreated) in the ViewModel, then the ViewModel still needs to report that the Property for the ObservableCollection has changed.

Just some thoughts.



回答2:

ObservableCollection already implements INotifyPropertyChanged, so you don't need to.