Tuesday, November 15, 2011

What is MVVM and why it's great for WPF applications

I just heard about MVVM overhearing some chatter after some people were talking about an interview, and now some articles from CodeProjet showed up in my email box. I had heard about MVC which is a standard design pattern that was used for the old MFC applications and is now avaiable for ASP.NET. The bindings features means you don't need a lot of code-behind to move data in and out of the database. In classic ASP, they would slap SQL in the middle of an ASP script. In ASP.NET, you would still need a code behind to move data from a data record into a form and back again. In WPF, a binding takes care of this data movement.
The key WPF features that support MVVM are:
  • WPF Bindings - each binding connects two properties (possibly on two different objects) so that if one of them changes, the other changes too.
  • WPF Data Templates, which convert non-visual data (ViewModel) into its visual representation (View).
  • WPF Commands (or MS Expression Blend SDK interactivity behaviors) serve to pass the events from the Views to the ViewModels.
WPF Apps With The Model-View-ViewModel Design Pattern
Josh Smith

The Evolution of Model-View-ViewModel
Ever since people started to create software user interfaces, there have been popular design patterns to help make it easier. For example, the Model-View-Presenter (MVP) pattern has enjoyed popularity on various UI programming platforms. MVP is a variation of the Model-View-Controller pattern, which has been around for decades. In case you have never used the MVP pattern before, here is a simplified explanation. What you see on the screen is the View, the data it displays is the model, and the Presenter hooks the two together. The view relies on a Presenter to populate it with model data, react to user input, provide input validation (perhaps by delegating to the model), and other such tasks. If you would like to learn more about the Model View Presenter, I suggest you read Jean-Paul Boodhoo's August 2006 Design Patterns column.
Back in 2004, Martin Fowler published an article about a pattern named Presentation Model (PM). The PM pattern is similar to MVP in that it separates a view from its behavior and state. The interesting part of the PM pattern is that an abstraction of a view is created, called the Presentation Model. A view, then, becomes merely a rendering of a Presentation Model. In Fowler's explanation, he shows that the Presentation Model frequently updates its View, so that the two stay in sync with each other. That synchronization logic exists as code in the Presentation Model classes.
In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler's Presentation Model, in that both patterns feature an abstraction of a View, which contains a View's state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.
In Glenn Block's excellent article "Prism: Patterns for Building Composite Applications with WPF" in the September 2008 issue, he explains the Microsoft Composite Application Guidance for WPF. The term ViewModel is never used. Instead, the term Presentation Model is used to describe the abstraction of a view. Throughout this article, however, I'll refer to the pattern as MVVM and the abstraction of a view as a ViewModel. I find this terminology is much more prevelant in the WPF and Silverlight communities.
Unlike the Presenter in MVP, a ViewModel does not need a reference to a view. The view binds to properties on a ViewModel, which, in turn, exposes data contained in model objects and other state specific to the view. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data.
The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model is completely oblivious to the fact that the ViewModel and view exist. This is a very loosely coupled design, which pays dividends in many ways, as you will soon see.

Why WPF Developers Love MVVM
Once a developer becomes comfortable with WPF and MVVM, it can be difficult to differentiate the two. MVVM is the lingua franca of WPF developers because it is well suited to the WPF platform, and WPF was designed to make it easy to build applications using the MVVM pattern (amongst others). In fact, Microsoft was using MVVM internally to develop WPF applications, such as Microsoft Expression Blend, while the core WPF platform was under construction. Many aspects of WPF, such as the look-less control model and data templates, utilize the strong separation of display from state and behavior promoted by MVVM.
The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and entirely remove the need for writing code in a ViewModel that directly updates a view. The data binding system also supports input validation, which provides a standardized way of transmitting validation errors to a view.
Two other features of WPF that make this pattern so usable are data templates and the resource system. Data templates apply Views to ViewModel objects shown in the user interface. You can declare templates in XAML and let the resource system automatically locate and apply those templates for you at run time. You can learn more about binding and data templates in my July 2008 article, "Data and WPF: Customize Data Display with Data Binding and WPF."
If it were not for the support for commands in WPF, the MVVM pattern would be much less powerful. In this article, I will show you how a ViewModel can expose commands to a View, thus allowing the view to consume its functionality. If you aren't familiar with commanding, I recommend that you read Brian Noyes's comprehensive article, "Advanced WPF: Understanding Routed Events and Commands in WPF," from the September 2008 issue.
In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free and fast regression testing, which helps reduce the cost of maintaining an application over time.
In addition to promoting the creation of automated regression tests, the testability of ViewModel classes can assist in properly designing user interfaces that are easy to skin. When you are designing an application, you can often decide whether something should be in the view or the ViewModel by imagining that you want to write a unit test to consume the ViewModel. If you can write unit tests for the ViewModel without creating any UI objects, you can also completely skin the ViewModel because it has no dependencies on specific visual elements.
Lastly, for developers who work with visual designers, using MVVM makes it much easier to create a smooth designer/developer workflow. Since a view is just an arbitrary consumer of a ViewModel, it is easy to just rip one view out and drop in a new view to render a ViewModel. This simple step allows for rapid prototyping and evaluation of user interfaces made by the designers.
From codeproject Here is the start, this article says it's been viewed about 10,000 times!

MVVM Pattern Made Simple

gives an overview of MVVM pattern, its usage and advantages


As many companies are switching from Win Forms to WPF/Silverlight, several project managers recently asked me almost identical questions about MVVM:
  • What is MVVM Pattern?
  • What are the advantages of the MVVM approach?
The purpose of this article is to answer these questions and to explain the MVVM pattern in the simplest possible way. I assume that the article readers have not had any previous exposure to the MVVM pattern but have some knowledge of WPF or Silverlight.
Time permitting, I plan to write more MVVM articles which will include comparison of different MVVM frameworks and introduce a new MVVM framework.

MVVM Overview

Model-View-ViewModel (MVVM) pattern splits the User Interface code into 3 conceptual parts - Model, View and ViewModel out of which the concept of the ViewModel is the new and the most exciting.
  • Model is a set of classes representing the data coming from the services or the database.
  • View is the code corresponding to the visual representation of the data the way it is seen and interacted with by the user.
  • ViewModel serves as the glue between the View and the Model. It wraps the data from the Model and makes it friendly for being presented and modified by the view. ViewModel also controls the View's interactions with the rest of the application (including any other Views).

ViewModel code can (and should) refer to the Model, but the Model classes (if separate from the ViewModel) should not be aware of the ViewModel. View should be aware of the ViewModel, but ViewModel should be not aware of the View. At the diagram above, the arrows are showing which MVVM part is aware of which.
Similar to the models in the older patterns, the Model within MVVM pattern is simply data coming from the service or the database. Quite often the Model can be built to be part of the ViewModel. Because of that, in our samples, we'll skip the model and concentrate primarily on the ViewModel, the View and interactions between them.

WPF Concepts Related to the MVVM Pattern, Communications between the View and the ViewModel

MVVM pattern became possible because of the following new concepts that came into being as part of the WPF (and later Silverlight).
  • WPF Bindings - each binding connects two properties (possibly on two different objects) so that if one of them changes, the other changes too.
  • WPF Data Templates, which convert non-visual data (ViewModel) into its visual representation (View).
  • WPF Commands (or MS Expression Blend SDK interactivity behaviors) serve to pass the events from the Views to the ViewModels.
WPF Bindings, WPF Commands and MS Expression Blend SDK interactivity functionality provide the necessary plumbing for communications between the View and the ViewModel. Another method can be employed for such communications - C# events can be used to trigger a change within a View when something happens within its ViewModel. This method should be avoided whenever possible because it implies code behind within the view (to register an event handler). Instead, one should use the bindings (perhaps combined with the triggers) to pass information about changes within the ViewModel to the View.
(follow link for more)
I didn't have time to follow all of these, but they look very good

No comments: