Wednesday, June 6, 2012

ModelView – ViewModel (MVVM)



Overview of the ModelView – ViewModel (MVVM) pattern and data-binding



In my own learning of WPF or any technology that I learn, I use the same approach and design principles that I would for a technology I know inside out. I have used winforms for years and I would be modest to say I know how to design a winform application the right way. It would be the approach I would use if I was developing an application in java swing. I would at the forefront of my design use the “model view controller” (MVC) pattern. The MVC pattern has been around since I was born and has been discussed and debated to death over the years. MVC aside I would use a number of other design patterns that fit the  bill for concern situations. For example: I would use command objects to do certain actions which could be wired up to menu items and/or buttons.

Model View Controller

The MVC pattern is a compound pattern, meaning that MVC is made up of other design patterns used together. MVC is made up of the “Mediator” and the “Observer” patterns (I and not going to discuss the details of these patterns as I want to keep to the subject matter, for more information on this patterns I recommend the Gang of Four web site and I might put a post together in the future).

Although MVC is a well established pattern, I have read other blogs and stuff in forums and the opinion of what MVC is, is very mixed. MVC in the .NET world seems to have become more wide spread over recent years which is good but MVC is not just about “Separation of Concerns” which some people I have worked along side believe. I can not remember where I got this from but the rules I follow are:

    Model = what it is.
    View = what it looks like.
    Controller = what it does.

MVC is a pattern and as such is a guideline and the implementations of the pattern vary. Variations of MVC exist like “Model-View-Presenter” (MVP) and “ModelView-ViewModel” (MVVM). In a very brief explanation:

MVC – The view sits at the top of the architecture, the controller sits below the view. The model sits below the controller. So the view knows about the controller, the controller knows the model. The view is notified when the model changes.

MVP – The controller is replaced with a presenter. The presenter sits at the same level as the view. The presenter listens to the events of both the view and the model and mediates the interactions between both the view and model.

MVVM – The controller is replaced with a view model. the view model sits below the UI layer. The view model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The view model pulls its data from the model(s) below.


 connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"

by
Guna