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.

I read a blog by Josh Smith on “the code project” once where he talked about MVC and WPF and he stated “lower the flamethrower”. I echo his comments.

If you put ten software architects into a room and have them discuss what the Model-View-Controller pattern is, you will end up with twelve different opinions. … Some of the purists out there will inevitably have qualms with what I refer to as “MVC”. Feel free to leave a flaming comment on the message board at the bottom of this Web page. I will gladly entertain different perspectives on what MVC means, but keep in mind that I do not care.

Data-binding

The word Data-binding used to bring back bad memories of using data-binding in older technologies. In Winforms .net 2.0, it was not perfect, it was ok for simple things like binding data grids and text boxes and drop down boxes but using a date time picker was painful. The .net framework contains a number of interfaces and classes (“system.componentmodel”) that allowed you to implement better data-binding support in your own objects.  Using a custom implementation of the observer pattern with a hybrid of the data-binding interfaces was more desirable in winforms. (the memories, the pain).

But in WPF, no need to be down about data-binding, because it is excellent. Though it has a learning curve.

Data-binding is in its own right an implementation of MVC. the view are the controls that are shown in UI. the model is the object you are binding to and the controller is the data-binding component. I think its important to think about data-binding in this way.

Why is MVVM different

I believe that MVVM pattern was developed by some Microsoft developers a few years ago when developing Expression Blend. The main difference with MVVM to MVC is that the ViewModel is built to serve the view and provide the view with the data and commands it needs. The viewModel is not a general object that could serve different views but is bespoke for each view. For the TDD’ers out there its easy to define the behaviour of a viewmodel and test using a test first approach. The ViewModel is a model for the view. And the real power comes in when you bind your ViewModel to your view in WPF.

The key thing to remember is that you have one and only one ViewModel per view. The view model communicates with the model (business logic, services whatever below it). The view does not need to know about any else in your architecture. Another major plus point is that you do not any code behind your view and the data-binding deals with the communication to the view model and what ever the view model exposes.

Thats it for a quick overview. I have a draft post that i am working on that will put this into concrete code.

68 thoughts on “Overview of the ModelView – ViewModel (MVVM) pattern and data-binding

  1. Russell:
    After reading a number of posts on mvc, mvvm, mvp ….it is refreshing to read your post, which summerizes the differences nicely.

    My thought is that the differences between these patterns are not that significant to warrant different names and whoever have added mvp or mvvm are just packing old wine in the new bottle!
    why can’t things be left at mvc with a small note saying: In wpf, the control of mvc is replaced by the binding component.

  2. I have question

    Everything is fine when “Model” has just one collection.
    But when “Model” has more than one collection and “Veiw”
    uses “Canvas” to present all objects from all collections.

    Should “ViewModel” combine all objects in one “Common collection” to simplify data binding?

    Or to avoid extra “Common collection”

    Is it better to change “Model” and put everything in one collection.

  3. Ghennadii, thanks for the post. To answer your question, your ViewModel is like a fascade, it can bring one of more models together and expose information to the view.

    For example, if you have a view for “customer details”, you could have a collection of customers displayed in a ListView plus a section of your view so you can edit the details (common master-detail pattern). When the user select a customer in the listview the selected customer information is displayed in the edit section of the view. Some of the information about the customer could their “Title” (mr, mrs, dr etc) and “Order”. The view model for this view would expose a collection of customers (CollectionView), a collection of “Titles” and “Order”. So you have 3 different collections.

    Now in the view, when the view is created, set the datacontext property in your view to the instance of your viewModel. In the xaml you would bind to the right properties on your viewmodel. Use the viewmodel to bring all the required model(s) together into one specific object for your view.

    Hope this helps

  4. I would like to be a little clear.
    View is graphis surface – canvas.
    To simplify “Model” let’s say
    “Model” has collection of rectangles and collection of lines
    no any reason to put all objects in one collection they are very different.
    View binding data in “ViewModel” and I do not understand how “ViewModel” should look like in that case?

    What I have done so far – all objects derived from base object
    in “VeiwModel” I created common collection put everything in one collection and bind “View” to it.

    It works.

    But I do not like that. I do not like extra collection. I have to support it.

    Simple question: Do I have to MVVM pattern or I have to use something else?
    Or I’ve done something wrong.

  5. why not partial class to build the ViewModel?

    because the definition of viewmodel classes have some definition of the data classes of datamodel , why not try to reduce some work, extending or making partial classes of the datamodel. completing them with command and etc.

  6. Nuno, I am not sure i understand your comment. Views, view-models, data models and commands all have different responsibilities. Where do partial classes come into this?

  7. data models and view models are different beasts. a single view model could aggregate different types of data models.

  8. Good work! Thank you!
    I always wanted to write in my blog something like that. Can I take part of your post to my blog?
    Of course, I will add backlink?

    Sincerely, Timur I. Alhimenkov

  9. Thanks for this article. Each time I read more about MVVM a little more of it sinks in. One of the things that our team has been struggling with has been the connection between the ViewModel and the Model – more specifically, is it common to use the Repository as the Model for the ViewModel? If you make a change in your View which updates the VM through databinding, do you in turn make this update to the Model (Repositiory) as well? If some views use some of the same data from the Model one would definately want these views to show the same data. Does this mean the Model is bound to the ModelView. I guess I’m really having trouble understanding that piece of the puzzle.

    Thanks again for your informative work here!
    Bill

    1. Ivan, yes it does make sense. I have on complex views, spilt my view up into controls and then use a “micro viewmodel/controller” for that control. Plus my main view will know about the “mirco viewmodel/controller”s. It also helps keep your classes small.

  10. Russel, thanks for answer. Now I have another question. If MVVM is good for WPF user control, then how to implement this control

    properly.

    The problem that I see is either we have to duplicate properties of ViewModel (VM) in the View, or we have to provide access to VM for

    the user of UserControl… I belive both of these options are not good and I don’t see another option…

    Let me explain both options in details:

    Imagine, we have control ‘MyControl’ which has corresponded view model ‘MyControlVM’:

    class MyControl : UserControl
    {
    private MyControlVM _vm;

    }

    Let’s say MyControl should have property ‘Value’. For example Value is evaluated when mouse moving over MyControl. In accordance to

    MVVM pattern: the property Value should be the part of VM.

    class MyControlVM
    {
    public double Value
    {
    get { … }
    set { … }
    }
    }

    User of MyControl must have access to this property.

    1) The first option is to provide corresponded property (and event handler for PropertyChanged event) in MyControl:

    class MyControl : UserControl
    {
    private MyControlVM _vm;

    // Duplicate property
    public double Value
    {
    get { return _vm.Value; }
    set { _vm.Value = value; }
    }

    public MyControl()
    {
    _vm = new MyControlVM();

    // Subscribe for VlaueChanged event of VM.
    _vm.ValueChanged += new ValueChangedHandler(this.VM_ValueChanged);
    }

    private void VM_ValueChanged()
    {
    // Notify all subscribers for ValueChanged event of MyControl.
    }


    }

    I think first option is not good, because View has duplicated code for wrapping corresponded properties of VM.

    2) The second option is to give user access to VM and let user directly use properties (methods, events) of VM. In this case:

    class MyControl : UserControl
    {
    private MyControlVM _vm;

    public MyControlVM VM
    {
    get { return _vm.Value; }
    }

    public MyControl()
    {
    _vm = new MyControlVM();
    }


    }

    This seems to be much simplier, but the problem is that user of MyControl should know about implementation of control. For example somewere in C# code:

    MyControl mc = new MyControl();
    mc.VM.Value = 123.456; // Why user should know about VM…

    and it could be even more challenging to access ‘Value’ property in XAML.

    The second option does not look as option at all.

    My question is how to implement such properties properly?

    Thank you.

    1. Ivan, I hope I can help with your problem. I would create a duplicate properties as you put it. My reasons are this are:

      1. The users of the control should not need to know about viewModel so no need to expose it. The outside world doesn’t need to know. This is a point that you have already made.
      2. Having your view simple delegate to the view model is a simple and clear behaviour, that to maintain this is easy and it would be clear to other developers if they looked at this code.
      3. Another way to see it, if you have an textbox on your view, you would bind it to a property on your viewmodel, you are doing the same thing.

      I didn’t like the second option. the view is a representation of your model. From a maintainence view point, you could refactor your view model and minimise your changes to within the control, where exposing its published interface could be painful to change.

      Again I hope this helps.

    1. Personally, I haven’t heard of the MVVP pattern. I have google’d it, but the context is talking MVVM pattern with silverlight.

  11. Sorry. It was a typo

    My question is “differences between MVP and MVVM”

    Thanks,
    Ramprasad

  12. Ramprasad, to hopefully answer your question. In MVP, the presenter is in control of the view and has knowledge of the view. Compared to MVVM, the view is bound to the ViewModel.

    MVVM is a tailored implementation of the presentation Model pattern (that M.Fowler has blogged about) for WPF.

    Although MVVM is all good, I now favor rolling my own MVP implementation, so that i can build my presentation logic the same for any view technology then i can simply swap the view technology. ie, Winforms to WPF to silverlight etc.

    Hope this helps 😉
    I hope

  13. Hi Russel,
    good to see the patterns explained in a mere few paragraphs; great summary.

    i’ve been wondering about MVVM and how things could be made easier.
    having to make duplicates of the properies in the ViewModel of the Model does sound the way this pattern is going, but to be honest, I don’t like it.
    Too much copying of code, it’s tedious and error prone.
    however i was thinking.. how about Linq to objects? where does this fit in? (does it even fit in?)

    could it be possible to simply use a mere Linq select statement on the Model it and create a dynamic, yet typed, ViewModel?
    have you considered this scenario?
    (to be honest i haven’t tried it yet)

    1. Thanks for the comment. I understand why you don’t like having the same properties in the model and the viewmodel. This has become more common with these days with domain entities, message objects and up to the presentation models also have the same properties. Each one of these types resides in its logical layer (domain, tranport, UI). The transport (message object) will be used by a mapper or some method that maps the data from the message to one of the other types (“domain entity” or “presentation model”). This is done to reduce the coupling.

      So the trade off is: do you want to have low coupling where you could refactor/rewrite/replace parts of you domain without having to change code in the ui. Or do you want to share types across your application. Personally I choice “low coupling” which means types need to be mapped as data is passed between layers. It does involve more code which is annoying. but i believe its worth it in the long run. As for linq for objects. I used linq in my mappers, but i still used strongly typed objects.

  14. I am still trying to figure out these patterns. Can any “M” pattern be used with WinForms, WebForms, WPF, and Silverlight? Also, how does code-behind fit into the architecture? Finally, does CSLA make sense for the Models?

    1. Bill, MVC can be used with winforms, web forms, wpf and silverlight. But certain technologies work better with certain variations of MVC. With Winforms and Webforms, i found the MVP a more suitable pattern, where MVVM works better with WPF and Silverlight.

      As for the code behind, ideally, you want as little code as possible in the code behind. This is easier with WPF and silverlight because the data binding mechanism can be configurated in xaml, keeping developers away from the code behind. As for Winforms, you need some code behind, thats why I prefer the MVP pattern with winforms, so that a form implements an interface and the presenter has knowledge of the view and tells the view what to do by its interface. This keeps most the UI logic in the presenter instead of the code behind. The code behind ends up with a small amount of code, typically methods with no more that a couple of lines code in them. This is similar for webforms, but I last done this with webforms about 3 years ago so i am bit rusty on the ins and outs. I use either MonoRail or ASP.NET MVC instead for web development these days.

      CSLA… I am not a fan, I have used it in an enterprise application and read two of Rockys books. You don’t need it or half the stuff the framework provides. Use POCOs instead with an ORM. I drive by code out using TDD/BDD and use the YAGNI rule. So i end up with fully tested code and only the code that is needed to do the job. Plus its maintainable. I don’t have a framework that i need to fight with to get it to work.

      Hope this helps

  15. Hello Russel

    I came across your post while looking for MVVM pattern.

    1) Can you please point what are the differences between Observer patterns and the MVVM pattern

    2) “The viewModel is not a general object that could serve different views but is bespoke for each view. ”

    Isnt this tight coupling. I think Observer does a nice job .. ( Document / View architecture in MFC )

    Thanks
    Sujay

    1. Hello Sujay. to answer your first question. the MVC pattern (and its variants) is a composite pattern and made up of the oberserver and mediator patterns (gang of four defination). When using WPF or Silverlight, the binding is using the observer pattern. If the binding is bound to a type that implements INotifyPropertyChanged or INotifyCollectionChanged interfaces, then it attaches itself as a listener. So the ViewModel is the source of data for the view. If the viewmodel implement the INotifyPropertyChange interface and fires the event from its properties setters, then the viewmodel is obserable. This is a primary benefit to using this pattern as the binding functionality is a making itself a listener to your observable type.

      To answer your second question, the view model is not tight coupled. The view only has to know about the one object being the view model. and view uses data binding to know about it, so really is just listening to one object, that brings together all the information the view needs to know about. this is why its specific for a view.

      Hope this helps

      Thanks

      Russell

      1. A key benefit of the ViewModel is that it can be a POCO that can be unit tested without any ui. The view which is the ui binds to it. Contrast that with a Presenter pattern where the presenter does direct updates to the state of screen controller. With the former you can rest without any graphical ui as part of the test with NUnit. With the latter it can be harder to test the logic in isolation.

        So the MVVM separation of layers is helpful. The actual view can change as the design changes. So the ViewModel is the ui logically – the view a skin. In such an approach the “coupled skin” is not a primary thing; incidental to the VM hence coupled to it.

  16. One question i have – since each View has a corresponding ViewModel… somehow that sounds like they could be “the same thing”… just thinking out loud here.
    Kinda like aspx pages with corres. codebehind .cs files.

    In other words: if every single view requires its very own ViewModel, is this not just moving the decoupling from the model into a different file? And in the end, just creating more code so we can feel like we’re decoupled?
    Ok I’ll be quiet now 😉

    1. The view and the viewmodel are not the same thing. They have different responsibilities. With the comparison with codebehind files, we do want to handle events from the UI etc which is done with the code behinds. One of the main problems with code behinds its testing them. With a separate ViewModel, you can test them without the view. (as a side note, I expose command objects from the view model so i can bind to them in the xaml.) So what is happens it that the code that would be in the code behind moves down into the viewmodel, although the code in the viewmodel is typically cleaner. So have we decoupled the code? yes. The view being dependant on the viewmodel as binding source. The viewmodel sits on top of the pyramid of complexity (service layers, model) by providing a single coherent class that exposes the relevant data and commands. MVVM is a variant of MVC, the view model combines the controller and model in the traditional sense.

    2. if every single view requires its very own ViewModel, is this not moving [complexity] into a different file?

      The end payoff is due to the automation that the databindings provide as well as the the maturity of the View’s layout framework.

      Where there is a good bi-directional declarative databinding framework the UI can then just be layout “skin” animated by the changes in the ViewModel. The databindings firing events into the command objects exposed on the ViewModel. The databindings write through to the domain objects exposed on the ViewModel. Ideally code is hand written to sync data into the UI nor bind UI controls to methods.

      With such a thin, layout orientated View we can have different users can load different Views which render a given ViewModel alternatively. The administrators View renders the buttons which delete from the system; the regular users View does not render such buttons.

      The ViewModel is observed by the View (actually the mature databindings technology; call it the View++). The View++ fires events into the ViewModel based on mouse clicks and key strokes. We trust that the bindings will successful call the correct ViewModel methods so we only have to focus NUnit testing on what happens when those methods are called.

      The ViewModel is then a presentationless user interface; an instance of a ViewModel has a one-to-one correspondence to a single View as it *is* the UI with the with the View being the skin (“presentation”) shown to the current user. The ViewModel state transitions are driven by user events pushed through the View++. We can ignore the View++ whilst perfecting our UI logic; as we trust the mature databindings framework to work when configured correctly in the View files. We concentrate on the ‘what’ of the UI not the ‘how’ of the UI.

      The ViewModel manipulates the model and interacts with the applications internal services. There is no less complexity in writing a good ViewModel than there is in writing a good Controller in MVC or a good Presenter in MVP; we just finesse things like rendering of alternative views and removes boring “sync some model to UI control” code.

  17. At the end of last year I implemented MVVM for the ZK Java AJAX framework and presented a patterns write up power point at the London ZK User Group meeting. The powerpoint is here http://dl.dropbox.com/u/2622674/zk/zk-mvvm.pdf which has where to google to find details articles with working source code for MVP, MVC and MVVM with pure Java. Actually trying to implement MVVM outside of .Net was very instructive. Doing it with a framework which supports MVP and MVC with databindings and then extending it to do “command bindings” was very enlightening. The experience lead me to christen the pattern “MVB – Model View Binder”.

  18. Honestly after reading all the documents over the internet the question is still in my mind:
    What is the difference between MVVM and MVC? by replacing controller with ViewModel what has been changed?
    What are the extra benefits of MVVM over MVC?

    1. There is actually a huge difference. MVC/MVP can both have binded data to your view. In MVC/MVP only your view implements an interface or abstract class. In MVVM, both the view and the view-model implement an interface. The two interact with each other through these interfaces. The view does not reference the concrete view-model and the view-model does not reference the concrete view class. This allows the view-model and the view to be swapped in and out as needed.

  19. Hi Russ, good to come across your blog. Looks like you’ve spend a lot of time blogging dude. They are good articles and good work of you.
    My two cents here:
    In mvc, a controller serves model to view on a one off basis. In other words, once the model data is delivered to the view and controller forgets about it. It will not automatically update either the view or the model if there’s been any changes.
    Whereas in MVVM, at least Microsoft’s implementation and KO.js, when either the view or the underlying viewmodel changes, their counterpart will be updated. This is something MVC wouldn’t offer. Hence MVC works better for the web apps due to HTTP’s stateless nature.
    Sorry if my points are irrelevant. On that bombshell, hope you and your family are doing well dude. Adios.

    1. Binjie 😉 its been a while. I think about MVC as a pattern rather then MVC as a web implementation (ASP.NET MVC / Monorail). As the Web implementation is more “Separation of concerns”. Being more of a windows guy and going back to Window 32 clients when binding was a mainly manual, the controller (or mirco-controllers) would mediate the view with the model with events and commands.

  20. “For the TDD’ers out their its easy to defined the behaviour of a viewmodel and test using a test first approach.”

    I hate to be picky, but what can I say? It’s an idiosyncrasy. I hated grammar in school, but now can’t stand to see mistakes in an otherwise excellent article. Kudos to you for your work. Please replace the word their with there. Behaviour is fine if you’re British, so I’ll let that slide. My big problem is the use of defined. Did you mean defend or define?

    1. @John Some people write code that machines can compile to give great functionality but cannot read thier own gramma errors. Only a bit of a (insert insult here) picks on gramma errors on free blog posts that are not proof read by a professional publishing house. Comments like this stop talented technologists form ever attempting to self publish. Take a hard look in the mirror and understand it annoys you as its so easy for you to see the mistakes so clearly it’s not easy for the guy writing and re-reading his work ten times a paragraph to see the same mistakes. Show some respect. It takes me a whole weekend to write an open source article and it will still contain errors – judge me on my content not my spelling and gramma.

      1. Good point. I am far from perfect, perhaps the furthest. Unfortunately in this case my grammar was okay, but word choice was very poor. The article was very helpful to me. I should have spent more effort in praise and less in criticism so as to not give the impression that I did. My hope was that I make the article better, not to discourage the authorship of articles. Thank you russelleast for your authorship and to Simon for your attempts to improve me.

    1. I should mention that to avoid unhelpful arguments about “thats not how i would do mvp/mvc/mvvm in framework x or language y” the ibm articles sticks to more specific/descriptive names for the patterns such as ‘passive view’ for mvp, ‘supervising controller’ for mvc and ‘presentation model’ for mvvm. I could have called the ‘supervising controller’ either mvc or mvvmp. Hopefully it is the comparison of the three patters that make the trade-offs clear and as discussed at the end which trade-off is going to give the best mileage depends on the circumstances of any given project.

  21. And it is actually considerably simpler to utilize
    so that you aren’t missing in the degrees and amounts of nested menu navigation and tens of buttons to push.

  22. I do not drop many responses, however i did some searching and
    wound up here Overview of the ModelView – ViewModel (MVVM) pattern and data-binding
    | Russell East’s blog. And I actually do have a couple of questions for you if it’s allright.
    Could it be only me or does it look as if like some of these comments
    come across like they are left by brain dead folks?

    😛 And, if you are posting at other online sites, I would like to keep up with everything fresh you have to post.
    Could you list of the complete urls of all your public sites like
    your linkedin profile, Facebook page or twitter feed?

    1. @roscoe so you want a private address to ask private questions and all you have to say is that other people commenting in public are brain dead? The spirit of a blog is public discussion. If your not brave enough to discuss in public hair a private consultant to give you training don’t ask for a bloggers email to ask private question when the purpose of blogging is to discuss in public to the general good.

Leave a reply to Shyam Cancel reply