MVVM – Should View Bind to Model Property or ViewModel?

entity-frameworkmvvmnet

I am starting a project with following technical environment :
.Net 4.0, Entity Framework 4.0, WPF with MVVM Architecture

I saw lots of examples on the net, some books with this environment. In some of the examples authors had this Idea :

  1. Viemodel will have an instance of Model class (Entity Framework Entity e.g. Person)
  2. Bind the WPF view controls to the properties of Model

While some authors did :

  1. Viemodel will expose all the properties of the model.
  2. Bind the WPF view controls to the properties of ViewModel rather than to the model
    directly.

So is it a good idea to let the view bind properties from model rather than viewmodel exposing its own? Or which is more preferred?

Best Answer

I think a lot of programmers first try to take the shortcut of binding directly to the model, but in my experience this has some major drawbacks. The primary problem is that if your entity model is persisted by NHibernate or similar, then as soon as the View updates the model property, then NHibernate could persist those changes to the database. That doesn't work well for edit-screens that have a Save/Cancel button. In actual fact, it may choose to wait and persist everything as a batch, but the idea is that when you change the model, you're committing your change.

So, you could still get away with binding directly to model properties on read-only screens, but then you're going to have an inconsistency.

Additionally, most models don't implement INotifyPropertyChanged so they may not be suitable binding targets if the state of the screen changes after the initial display.

Given the ease of auto-properties, I suggest always binding the View to the ViewModel, not to the Model. It's consistent, simple, and gives you the most flexibility to support changes in the future.