Search code examples
c#wpfmvvmmodelviewmodel

In WPF, a ViewModel have a reference to a Model


Assume that there's a PIModel (i.e. Personal Information Model) and a ViewModel (contains some information from PIModel and other).

public PIModel
{
    private string firstName;
    public string FirstName { get; set; }

    private string lastName;
    public string LastName { get; set; }

    ... // other
}

The FirstName and LastName properties need to be bound to View, so I have two questions:

  • Does the ViewModel have a property reference to a PIModel instance?
  • If so, does the ViewModel have property references to PIModel.FirstName and PIModel.LastName?

I learned that implementing INotifyPropertyChanged in the Model is not recommended.


Solution

  • After a few years practicing MVVM, I would nuance a bit the answer, even if it is not 100% MSDN compliant.

    I would strongly agree with this reccomandation: do not implement the INotifyPropertyChanged in Model.

    And I would explain why: if your model is nothing but properties and INotifyPropertyChanged, what is its role in term of responsability? (Think about Single Responsability Principle: http://en.wikipedia.org/wiki/Single_responsibility_principle)

    Let's take your example: if you use INotifyPropertyChanged in PIModel, then the role of PIModel is to present your data to your view. And by the way, what's the role of a ViewModel in the MSDN definition? You got it: present your data to your view.

    So in the end, if you use both Model and ViewModel to present your data, the role of each component will blur, and you will have some ideas like "well, I think here I do no even need a ViewModel". The data presentation responsability will be set in different conceptual class.

    In my opiniion if you have this kind of thought, you need ONLY ViewModel (but probably a bigger ViewModel containing beyond others PIViewModel). Do not build an anemic Model (model with only properties and no responsability at all), because it will complexify your code and add no value.

    Use a Model only if you add some other responsability to your object, and not display responsability (because it belongs to a ViewModel) but rather real business responsability.

    So if the most of data is get from server, and the most of business responsability is on the server, it will be logical for me to see mainly ViewModel in your client application.

    Hope it helps.