Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am starting a project with following technical environment : .Net 4.0, Entity

ID: 642194 • Letter: I

Question

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 :

Viemodel will have an instance of Model class (Entity Framework Entity e.g. Person)
Bind the WPF view controls to the properties of Model
While some authors did :

Viemodel will expose all the properties of the model.
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 property from model rather than viewmodel exposing it's own? Or which is more preferred?

Explanation / 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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote