BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News MVVM Frameworks For .NET

MVVM Frameworks For .NET

This item in japanese

Bookmarks

Model-View-ViewModel is an architectural pattern mainly used in WPF, Silverlight and WP7 development whose aim is to virtually remove all the code-behind from the View layer. Interactive Designers can focus on UX needs using XAML and create bindings to the ViewModel, which is written and maintained by application developers.

MVVM is a specific implementation of the more general Presentation Pattern. MVVM ViewModel comprises of conceptual models rather than data models, and all the business logic and other operations are done within the Model and the ViewModel. There are many Frameworks which enable this. Some of them are -

Open Source

  • PRISM – provided by Microsoft. Works with MEF/Unity for dependency injection, has composite commands and is extensible. Detailed tutorials and walkthroughs at MSDN
  • MVVM Light Toolkit – has Project and Item templates for Visual Studio and Expression Blend. Read more here and refer tutorials on working with VS and Expression Blend.
  • Caliburn Micro – supports ViewModel-First and View-First development, Asynchronous programming through co-routines.
  • Simple MVVM Toolkit – provides VS Project and Item Templates, Dependency Injection, support for Deep cloning and Property Association between Model and ViewModel
  • Catel – includes Project and Item templates, user controls and enterprise library classes. Supports Dynamic View Model injection, lazy loading of view models and validations. Also sports WP7 specific view model services

Closed Source

  • Intersoft ClientUI – paid – supports only WPF and Silverlight, although, apart from MVVM framework, it also provides several other features.
  • Vidyano – free but not open source. Has Entity mapped/virtual Persistent Objects (data containers), business rules and in-built ACL based security

For an introduction to MVVM, refer to the following material -

One of the biggest benefits of using MVVM is the separation of concerns, so that the UX designers and the Application developers can work in parallel. On the other hand, concerns are that it is an overkill for simpler UI operations, data-bindings are somewhat harder to debug and potential performance issues if large number of bindings are used.

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • Adding Valued Content

    by J B,

  • Signs you might be doing MVVM wrong:

    by Jonathan Allen,

    • Adding Valued Content

      by J B,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      honestly, my 10 yr old son could have put this together using wiki.
      have we really sunk to this kind of journalism?
      i'd either pull this article or beef it up with some real content.

    • Re: Adding Valued Content

      by Roopesh Shenoy,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Thank you for your feedback JB.

      The idea was to introduce MVVM in the context of .NET and provide various frameworks that support this. However, per your feedback, I have added more details about each of the frameworks, as well as links to additional educational content. Hope you find this useful.

    • Signs you might be doing MVVM wrong:

      by Jonathan Allen,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      1. You have a model and a view-model with the same name.

      View-models are not supposed to be wrappers around models. The job of a view-model is to broker requests for external services such as the loading and saving of data. The data itself, as well as validation and most of the business logic, should be in the models.

      I can’t emphasize this enough. Whenever you create a view-model that wraps a model by delegation you introduce a huge hole in your API. Specially, anything with a direct reference to the model can change a property in such a way that the view-model and thus the UI are never notified. Likewise, any changes to calculated fields in the model won’t be propagated back to the view-model.

      2. You have a view and a view-model with the same name.

      Ideally view-models are agnostic to the screens they are used by. This is especially true in a WPF application where multiple windows may be sharing the same instance of a view-model.

      For smaller applications such you may only need a single view-model for the whole application. For larger applications you may need one for the main functionality and one for each secondary aspect such as configuration management.

      3. You have no code behind.

      In absolute terms code behind is neither a good nor a bad thing. It is merely a place to put logic that is specific to a single view or control. So when I see a view with no code-behind at all I immediately check for the following mistakes:

      * Does the view-model touch specific controls by name?
      * Is the view-model being given access to controls via a command parameter?
      * Is EventToCommand or another leaky behavior being used in place of simple event handler?

      EventToCommand from MVVM Light is especially bad because it will prevent controls from being garbage collected after they are removed from the screen.

      4. View-models are listening to property changed notifications

      If a model has a longer life-span then the view-model that listens to its events then you probably have a memory leak. Unlike views which have an unloaded event, view-models don’t have a good story for life-cycle management. So if they attach an event to a model that may out-last them then the view-model will be leaked.

    • Re: Signs you might be doing MVVM wrong:

      by Geert Depickere,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Jonathan,

      When you say "view-models ... wrappers around models", are you talking about the approach you often see where an instance of a Model is put in a View-Model property and the view then binds directly to the properties of that instance?

      In that approach, it looks like you are doing data binding to the View-Model but in reality you are binding to the Model (proof of that is that the databinding no longer works if e.g. you rename one of the properties of the Model class...).

      It this is what you are referring to, I totally agree. If so, can you elaborate on the alternative?

    • Re: Signs you might be doing MVVM wrong:

      by Jonathan Allen,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Binding through a view-model to a model is expected. For example: {Binding DataContext.ActiveCustomer.FirstName} where ActiveCustomer is a property on the view-model. Aside from the lack of static type checking this works remarkably well. XAML was made for this kind of stuff.

      What concerns me is code like this:


      public string FirstName
      {
      get { return _customer.FirstName; }
      set
      {
      if (value = = _customer.FirstName)
      return;
      _customer.FirstName = value;
      base.OnPropertyChanged("FirstName");
      }
      }


      source: msdn.microsoft.com/en-us/magazine/dd419663.aspx

      Bugs I see all the time:

      1. Someone directly changes _customer.FirstName. Since the change wasn't done via the CustomerViewModel the UI is not notified about the change.

      2. Changing _customer.FirstName has the side effect of updating _customer.FullName. Again, CustomerViewModel doesn't know it happened so it cannot notify the UI.

      Given how incredibly error prone this style is, there is simply no way to justify it. I'm not sure what Josh Smith was thinking when he write the MSDN article, but has done a great disservice to the developer community.

    • Re: Signs you might be doing MVVM wrong:

      by Roopesh Shenoy,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      I haven't done this before, so I don't understand this - why is base.OnPropertyChanged("FirstName") really needed? Isn't the framework supposed to handle it?

      Flex has a much better UI binding model - as long as the properties you create are declared as bindable, the UI gets updated automatically when the property return values get updated (even if its a complex property with a lot of logic before returning a get value). That's much simpler for the developer.

      For eg. (just ignore for a moment that I declared a public variable) the following simple component displaying the customer's name just works, even if you modify the customer name, or just pass a new customer object to this component.

      <?xml version="1.0" encoding="utf-8"?>
      <s:BorderContainer>
      <fx:Script>
      <![CDATA[

      [Bindable]
      public var customer:Customer = new Customer();
      ]]>
      </fxScript>
      <s:Label text="{customer.Name}" />
      <BorderContainer></BorderContainer>


      I can easily imagine how this can be refactored to look more like the MVVM pattern, but the point is, the UI takes care of the property changes and doesn't need special events to be thrown. </![cdata[

      ></fx:script></s:bordercontainer></?xml>

    • Re: Signs you might be doing MVVM wrong:

      by Roopesh Shenoy,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Pardon the code formatting above, there is no real way to edit it :(.

    • Re: Signs you might be doing MVVM wrong:

      by Jonathan Allen,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      There are AOP style rewriters that allow you to write your C# code like Flex, but they aren't supported by Microsoft so few people use them. Instead we have to manually raise the events needed to notify the UI of changes.

      Basically it comes down to the difference between general purpose languages like C# and a language designed specifically for UI development.

    • Re: Signs you might be doing MVVM wrong:

      by Chris Clark,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Jonathan,
      For those who are new/inexperienced using MVVM, do you have specific examples to demonstrate doing MVVM right with regards to the 4 points you listed?

      Chris

    • Re: Signs you might be doing MVVM wrong:

      by Rob Eisenberg,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      @Chris

      You should take Jonathan's "advice" with a grain of salt. Most people who are internationally recognized as experts in UI Architecture, and MVVM specifically, would disagree strongly with points 2 and 3. Regarding point 1, it's usually an over-complication, but sometimes there are justifications for this type of design. It's true that developers do it far too often for no advantage. But it's not always a bad practice. The same thing pretty much goes for point 4. It's not the best architecture in the majority of cases, but there are some reasons to do this.

      If you are getting started, I would recommend the following web casts:

      Understanding the Model-View-ViewModel Pattern by Laurent Bugnion channel9.msdn.com/Events/MIX/MIX10/EX14
      Build Your Own MVVM Framework by Rob Eisenberg (that's me) channel9.msdn.com/Events/MIX/MIX10/EX15

      Both of these talks are among the most viewed and highest rated talks from Mix 2010.

      If you want to look at a sample project built with Caliburn.Micro (mentioned in the article), check this out coproject.codeplex.com/ There is code and a 14 part article series. You can also check out some of the Caliburn.Micro contest winners here: caliburnmicro.codeplex.com/wikipage?title=2010%... If you want to read some more theory on the subject, check out www.caliburnproject.org/ In the bottom left corner are links to a series of articles on MVVM. In particular, the Interlude article, devlicio.us/blogs/rob_eisenberg/archive/2010/05... will provide you with a much better list of frameworks and learning resources than this infoq article.

    • Re: Signs you might be doing MVVM wrong:

      by Roopesh Shenoy,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Thanks Rob.

      I had some time to form a perspective, by understanding how RIA services generates the ViewModel code. I definitely don't say that's the best design (since it is mainly for CRUD applications) but it is something provided by Microsoft and decently well out-of-the-box. I also know this is for silverlight whereas the above discussion was probably for WPF (especially when model changes are supposed to affect view-model too), but none-the-less -

      1. There is a direct 1-1 mapping between Models and ViewModels. The workaround for calculated fields is that you put them in a shared partial class on the server side, and they just get copied to the client side as well (dirty, but it works, and it is the tools that copy the files)

      2. Views and View-models are completely independent, the view-models do not handle the user controls directly. You can, however, use annotations on the view-model which can be used in auto-generation of dataform fields.

      3. You do have code behind to control the View logic, the View-models only handle the network calls and fetching data it is the code-behind in the view that needs to handle the user interaction. It is possible to write minimal UI with only XAML based domainservice calls, but for any useful interface, you will probably revert to the code-behind.

      Besides this, there are service methods acting as wrappers around the models and this is what the View-models actually call (they do not interact with the models directly). I can presume that this is needed in silverlight since data has to be serialized before being sent.

      I can't see why a similar approach cannot be used even for WPF. Is there a reason you can see why someone shouldn't use RIA services or modify the way it is used?

    • Vidyano v3

      by Gunther Clauwaert,

      Your message is awaiting moderation. Thank you for participating in the discussion.

      Hi Roopert, Thanks for mentioning Vidyano. Just to inform you that a new release and a new website will be released by May 4th 2012 latest. This release is a major one including a lot of new features and techniques. Feel free to download it from the VS gallery and please let us know what you think about it. Regards, Gunther

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT