In MVVM model should the model implement INotifyPropertyChanged interface?

Syed picture Syed · Aug 3, 2011 · Viewed 24.2k times · Source

I have clear idea about View and ViewModel in MVVM pattern. I am planning to implement MVVM pattern in my application. I'm facing an issue regarding the model. I have .xml file which is parsed and the information is displayed in the View.

I need to be notified about the changes in the model for the first time only. From onwards on demand I need to be notified.

So how to implement the model?

Should I implement INotifyPropertyChanged interface in model class also? (I read that model should not implement INotifyPropertyChanged interface, since it is WPF specific)

Answer

akjoshi picture akjoshi · Aug 3, 2011

Implementing INotifyPropertyChanged in Models is totally acceptable -

Typically, the model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection<T> class, which provides an implementation of the INotifyCollectionChanged interface.

Although its up to you to decide whether you want that type of implementation or not, but remember -

What if your model classes do not implement the required interfaces?

Sometimes you will need to work with model objects that do not implement the INotifyPropertyChanged, INotifyCollectionChanged, IDataErrorInfo, or INotifyDataErrorInfo interfaces. In those cases, the view model may need to wrap the model objects and expose the required properties to the view. The values for these properties will be provided directly by the model objects. The view model will implement the required interfaces for the properties it exposes so that the view can easily data bind to them.

Taken from - http://msdn.microsoft.com/en-us/library/gg405484(PandP.40).aspx

I have worked in some projects where we haven't implemented INotifyPropertyChanged in our models and due to this we faced a lot of issues; unnecessary duplication of properties was needed in VM and at the same time we had to update the underlying object(with updated values) before passing them to BL/DL.

You will face problems specially if you need to work with collection of your model objects(say in an editable grid or list) or complex models; model objects won't be updated automatically and you will have to manage all that in your VM.