July 2010

Volume 25 Number 07

Design Patterns - Problems and Solutions with Model-View-ViewModel

By Robert McCarter | July 2010

Windows Presentation Foundation (WPF) and Silverlight provide rich APIs for building modern applications, but understanding and applying all the WPF features in harmony with each other to build well-designed and easily maintained apps can be difficult. Where do you start? And what is the right way to compose your application?

The Model-View-ViewModel (MVVM) design pattern describes a popular approach for building WPF and Silverlight applications. It’s both a powerful tool for building applications and a common language for discussing application design with developers. While MVVM is a really useful pattern, it’s still relatively young and misunderstood.

When is the MVVM design pattern applicable, and when is it unnecessary? How should the application be structured? How much work is the ViewModel layer to write and maintain, and what alternatives exist for reducing the amount of code in the ViewModel layer? How are related properties within the Model handled elegantly? How should you expose collections within the Model to the View? Where should ViewModel objects be instantiated and hooked up to Model objects?

In this article I’ll explain how the ViewModel works, and discuss some benefits and issues involved in implementing a ViewModel in your code. I’ll also walk you through some concrete examples of using ViewModel as a document manager for exposing Model objects in the View layer.

Model, ViewModel and View

Every WPF and Silverlight application I’ve worked on so far had the same high-level component design. The Model was the core of the application, and a lot of effort went into designing it according to object-oriented analysis and design (OOAD) best practices.

For me the Model is the heart of the application, representing the biggest and most important business asset because it captures all the complex business entities, their relationships and their functionality.

Sitting atop the Model is the ViewModel. The two primary goals of the ViewModel are to make the Model easily consumable by the WPF/XAML View and to separate and encapsulate the Model from the View. These are excellent goals, although for pragmatic reasons they’re sometimes broken.

You build the ViewModel knowing how the user will interact with the application at a high level. However, it’s an important part of the MVVM design pattern that the ViewModel knows nothing about the View. This allows the interaction designers and graphics artists to create beautiful, functional UIs on top of the ViewModel while working closely with the developers to design a suitable ViewModel to support their efforts. In addition, decoupling between View and ViewModel also allows the ViewModel to be more unit testable and reusable.

To help enforce a strict separation between the Model, View and ViewModel layers, I like to build each layer as a separate Visual Studio project. Combined with the reusable utilities, the main executable assembly and any unit testing projects (you have plenty of these, right?), this can result in a lot of projects and assemblies, as illustrated in Figure 1.

Figure 1 The Components of an MVVM Application

Figure 1 The Components of an MVVM Application

Given the large number of projects, this strict-separation approach is obviously most useful on large projects. For small applications with only one or two developers, the benefits of this strict separation may not outweigh the inconvenience of creating, configuring and maintaining multiple projects, so simply separating your code into different namespaces within the same project may provide more than sufficient isolation.

Writing and maintaining a ViewModel is not trivial and it should not be undertaken lightly. However, the answer to the most basic questions—when should you consider the MVVM design pattern and when is it unnecessary—is often found in your domain model.

In large projects, the domain model may be very complex, with hundreds of classes carefully designed to work elegantly together for any type of application, including Web services, WPF or ASP.NET applications. The Model may comprise several assemblies working together, and in very large organizations the domain model is sometimes built and maintained by a specialized development team.

When you have a large and complex domain model, it’s almost always beneficial to introduce a ViewModel layer.

On the other hand, sometimes the domain model is simple, perhaps nothing more than a thin layer over the database. The classes may be automatically generated and they frequently implement INotifyPropertyChanged. The UI is commonly a collection of lists or grids with edit forms allowing the user to manipulate the underlying data. The Microsoft toolset has always been very good at building these kinds of applications quickly and easily.

If your model or application falls into this category, a ViewModel would probably impose unacceptably high overhead without sufficiently benefitting your application design.

That said, even in these cases the ViewModel can still provide value. For example, the ViewModel is an excellent place to implement undo functionality. Alternatively, you can choose to use MVVM for a portion of the application (such as document management, as I’ll discuss later) and pragmatically expose your Model directly to the View.

Why Use a ViewModel?

If a ViewModel seems appropriate for your application, there are still questions to be answered before you start coding. One of the first is how to reduce the number of proxy properties.

The separation of the View from the Model promoted by the MVVM design pattern is an important and valuable aspect of the pattern. As a result, if a Model class has 10 properties that need to be exposed in the View, the ViewModel typically ends up having 10 identical properties that simply proxy the call to the underlying model instance. These proxy properties usually raise a property-changed event when set to indicate to the View that the property has been changed.

Not every Model property needs to have a ViewModel proxy property, but every Model property that needs to be exposed in the View will typically have a proxy property. The proxy properties usually look like this:

public string Description {
  get { 
    return this.UnderlyingModelInstance.Description; 
  set {
    this.UnderlyingModelInstance.Description = value;

Any non-trivial application will have tens or hundreds of Model classes that need to be exposed to the user through the ViewModel in this fashion. This is simply intrinsic to the separation provided by MVVM.

Writing these proxy properties is boring and therefore error-prone, especially because raising the property-changed event requires a string that must match the name of the property (and will not be included in any automatic code refactoring). To eliminate these proxy events, the common solution is to expose the model instance from the ViewModel wrapper directly, then have the domain model implement the INotifyPropertyChanged interface:

public class SomeViewModel {
  public SomeViewModel( DomainObject domainObject ) {
      "The domain object to wrap must not be null");
    this.WrappedDomainObject = domainObject;
  public DomainObject WrappedDomainObject { 
    get; private set; 

Thus, the ViewModel can still expose the commands and additional properties required by the view without duplicating Model properties or creating lots of proxy properties. This approach certainly has its appeal, especially if the Model classes already implement the INotifyPropertyChanged interface. Having the model implement this interface isn’t necessarily a bad thing and it was even common with Microsoft .NET Framework 2.0 and Windows Forms applications. It does clutter up the domain model, though, and wouldn’t be useful for ASP.NET applications or domain services.

With this approach the View has a dependency on the Model, but it’s only an indirect dependency through data binding, which does not require a project reference from the View project to the Model project. So for purely pragmatic reasons this approach is sometimes useful.

However, this approach does violate the spirit of the MVVM design pattern, and it reduces your ability to introduce new ViewModel-specific functionality later (such as undo capabilities). I’ve encountered scenarios with this approach that caused a fair bit of rework. Imagine the not-uncommon situation where there’s a data binding on a deeply nested property. If the Person ViewModel is the current data context, and the Person has an Address, the data binding might look something like this:

{Binding WrappedDomainObject.Address.Country}

If you ever need to introduce additional ViewModel functionality on the Address object, you’ll need to remove data binding references to WrappedDomainObject.Address and instead use new ViewModel properties. This is problematic because updates to the XAML data binding (and possibly the data contexts as well) are hard to test. The View is the one component that doesn’t have automated and comprehensive regression tests.

Dynamic Properties

My solution to the proliferation of proxy properties is to use the new .NET Framework 4 and WPF support for dynamic objects and dynamic method dispatch. The latter allows you to determine at run time how to handle reading or writing to a property that does not actually exist on the class. This means you can eliminate all the handwritten proxy properties in the ViewModel while still encapsulating the underlying model. Note, however, that Silverlight 4 does not support binding to dynamic properties.

The simplest way to implement this capability is to have the ViewModel base class extend the new System.Dynamic.DynamicObject class and override the TryGetMember and TrySetMember methods. The Dynamic Language Runtime (DLR) calls these two methods when the property being referenced does not exist on the class, allowing the class to determine at run time how to implement the missing properties. Combined with a small amount of reflection, the ViewModel class can dynamically proxy the property access to the underlying model instance in only a few lines of code:

public override bool TryGetMember(
  GetMemberBinder binder, out object result) {

  string propertyName = binder.Name;
  PropertyInfo property = 

  if( property==null || property.CanRead==false ) {
    result = null;
    return false;

  result = property.GetValue(this.WrappedDomainObject, null);
  return true;

The method starts by using reflection to find the property on the underlying Model instance. (For more details, see the June 2007 “CLR Inside Out” column “Reflections on Reflection”.) If the model doesn’t have such a property, then the method fails by returning false and the data binding fails. If the property exists, the method uses the property information to retrieve and return the Model’s property value. This is more work than the traditional proxy property’s get method, but this is the only implementation you need to write for all models and all properties.

The real power of the dynamic proxy property approach is in the property setters. In TrySetMember, you can include common logic such as raising property-changed events. The code looks something like this:

public override bool TrySetMember(
  SetMemberBinder binder, object value) {

  string propertyName = binder.Name;
  PropertyInfo property = 

  if( property==null || property.CanWrite==false )
    return false;

  property.SetValue(this.WrappedDomainObject, value, null);

  return true;

Again, the method starts by using reflection to grab the property from the underlying Model instance. If the property doesn’t exist or the property is read-only, the method fails by returning false. If the property exists on the domain object, the property information is used to set the Model property. Then you can include any logic common to all property setters. In this sample code I simply raise the property-changed event for the property I just set, but you can easily do more.

One of the challenges of encapsulating a Model is that the Model frequently has what Unified Modeling Language calls derived properties. For example, a Person class probably has a BirthDate property and a derived Age property. The Age property is read-only and automatically calculates the age based on the birth date and the current date:

public class Person : DomainObject {
  public DateTime BirthDate { 
    get; set; 

  public int Age {
    get {
      var today = DateTime.Now;
      // Simplified demo code!
      int age = today.Year - this.BirthDate.Year;
      return age;

When the BirthDate property changes, the Age property also implicitly changes because the age is derived mathematically from the birth date. So when the BirthDate property is set, the ViewModel class needs to raise a property-changed event for both the BirthDate property and the Age property. With the dynamic ViewModel approach, you can do this automatically by making this inter-property relationship explicit within the model.

First, you need a custom attribute to capture the property relationship:

[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
public sealed class AffectsOtherPropertyAttribute : Attribute {
  public AffectsOtherPropertyAttribute(
    string otherPropertyName) {
    this.AffectsProperty = otherPropertyName;

  public string AffectsProperty { 
    private set; 

I set AllowMultiple to true to support scenarios where a property can affect multiple other properties. Applying this attribute to codify the relationship between BirthDate and Age directly in the model is straightforward:

public DateTime BirthDate { get; set; }

To use this new model metadata within the dynamic ViewModel class, I can now update the TrySetMember method with three additional lines of code, so it looks like this:

public override bool TrySetMember(
  SetMemberBinder binder, object value) {
  var affectsProps = property.GetCustomAttributes(
    typeof(AffectsOtherPropertyAttribute), true);
  foreach(AffectsOtherPropertyAttribute otherPropertyAttr 
    in affectsProps)

With the reflected property information already in hand, the GetCustomAttributes method can return any AffectsOtherProperty attributes on the model property. Then the code simply loops over the attributes, raising property-changed events for each one. So changes to the BirthDate property through the ViewModel now automatically raise both BirthDate and Age property-changed events.

It’s important to realize that if you explicitly program a property on the dynamic ViewModel class (or, more likely, on model-specific derived ViewModel classes), the DLR will not call the TryGetMember and TrySetMember methods and will instead call the properties directly. In that case, you lose this automatic behavior. However, the code could easily be refactored so that custom properties could use this functionality as well.

Let’s return to the problem of the data binding on a deeply nested property (where the ViewModel is the current WPF data context) that looks like this:

{Binding WrappedDomainObject.Address.Country}

Using dynamic proxy properties means the underlying wrapped domain object is no longer exposed, so the data binding would actually look like this:

{Binding Address.Country}

In this case, the Address property would still access the underlying model Address instance directly. However, now when you want to introduce a ViewModel around the Address, you simply add a new property on the Person ViewModel class. The new Address property is very simple:

public DynamicViewModel Address {
  get {
    if( addressViewModel==null )
      addressViewModel = 
        new DynamicViewModel(this.Person.Address);
    return addressViewModel;

private DynamicViewModel addressViewModel;

No XAML data bindings need to be changed because the property is still called Address, but now the DLR calls the new concrete property rather than the dynamic TryGetMember method. (Notice that the lazy instantiation within this Address property is not thread-safe. However, only the View should be accessing the ViewModel and the WPF/Silverlight view is single-threaded, so this is not a concern.)

This approach can be used even when the model implements INotifyPropertyChanged. The ViewModel can notice this and choose not to proxy property-changed events. In this case, it listens for them from the underlying model instance and then re-raises the events as its own. In the constructor of the dynamic ViewModel class, I perform the check and remember the result:

public DynamicViewModel(DomainObject model) {
  Contract.Requires(model != null, 
    "Cannot encapsulate a null model");
  this.ModelInstance = model;

  // Raises its own property changed events
  if( model is INotifyPropertyChanged ) {
    this.ModelRaisesPropertyChangedEvents = true;
    var raisesPropChangedEvents = 
      model as INotifyPropertyChanged;
    raisesPropChangedEvents.PropertyChanged +=
      (sender,args) => 

To prevent duplicate property-changed events, I also need to make a slight modification to the TrySetMember method.

if( this.ModelRaisesPropertyChangedEvents==false )

So you can use a dynamic proxy property to dramatically simplify the ViewModel layer by eliminating standard proxy properties. This significantly reduces coding, testing, documentation and long-term maintenance. Adding new properties to the model no longer requires updating the ViewModel layer unless there is very special View logic for the new property. Additionally, this approach can solve difficult issues like related properties. The common TrySetMember method could also help you implement an undo capability because user-driven property changes all flow through the TrySetMember method.

Pros and Cons

Many developers are leery of reflection (and the DLR) because of performance concerns. In my own work I haven’t found this to be a problem. The performance penalty for the user when setting a single property in the UI is not likely to be noticed. That may not be the case in highly interactive UIs, such as multi-touch design surfaces.

The only major performance issue is in the initial population of the view when there are a large number of fields. Usability concerns should naturally limit the number of fields you’re exposing on any screen so that the performance of the initial data bindings through this DLR approach is undetectable.

Nevertheless, performance should always be carefully monitored and understood as it relates to the user experience. The simple approach previously described could be rewritten with reflection caching. For additional details, see Joel Pobar’s article in the July 2005 issue of MSDN Magazine.

There is some validity to the argument that code readability and maintainability are negatively affected using this approach because the View layer seems to be referencing properties on the ViewModel that don’t actually exist. However, I believe the benefits of eliminating most of the hand-coded proxy properties far outweigh the problems, especially with proper documentation on the ViewModel.

The dynamic proxy property approach does reduce or eliminate the ability to obfuscate the Model layer because the properties on the Model are now referenced by name in the XAML. Using traditional proxy properties does not limit your ability to obfuscate the Model because the properties are referenced directly and would be obfuscated with the rest of the application. However, as most obfuscation tools do not yet work with XAML/BAML, this is largely irrelevant. A code cracker can start from the XAML/BAML and work into the Model layer in either case.

Finally, this approach could be abused by attributing model 
properties with security-related metadata and expecting the ViewModel to be responsible for enforcing security. Security doesn’t seem like a View-specific responsibility, and I believe this is placing too many responsibilities on the ViewModel. In this case, an aspect-oriented approach applied within the Model would be more suitable.


Collections are one of the most difficult and least satisfactory aspects of the MVVM design pattern. If a collection in the underlying Model is changed by the Model, it’s the responsibility of the ViewModel to somehow expose the change so that the View can update itself appropriately.

Unfortunately, in all likelihood the Model does not expose collections that implement the INotifyCollectionChanged interface. In the .NET Framework 3.5, this interface is in the System.Windows.dll, which strongly discourages its use in the Model. Fortunately, in the .NET Framework 4, this interface has migrated to System.dll, making it much more natural to use observable collections from within the Model.

Observable collections in the Model open up new possibilities for Model development and could be used in Windows Forms and Silverlight applications. This is currently my preferred approach because it’s much simpler than anything else, and I’m happy the INotifyCollectionChanged 
interface is moving to a more common assembly.

Without observable collections in the Model, the best that can be done is to expose some other mechanism—most likely custom events—on the Model to indicate when the collection has changed. This should be done in a Model-specific way. For example, if the Person class had a collection of addresses it could expose events such as:

public event EventHandler<AddressesChangedEventArgs> 
public event EventHandler<AddressesChangedEventArgs> 

This is preferable to raising a custom collection event designed specifically for the WPF ViewModel. However, it’s still difficult to expose collection changes in the ViewModel. Likely, the only recourse is to raise a property-changed event on the entire ViewModel collection property. This is an unsatisfactory solution at best.

Another problem with collections is determining when or if to wrap each Model instance in the collection within a ViewModel instance. For smaller collections, the ViewModel may expose a new observable collection and copy everything in the underlying Model collection into the ViewModel observable collection, wrapping each Model item in the collection in a corresponding ViewModel instance as it goes. The ViewModel might need to listen for collection-changed events to transmit user changes back to the underlying Model.

However, for very large collections that will be exposed in some form of virtualizing panel, the easiest and most pragmatic approach is just to expose the Model objects directly.

Instantiating the ViewModel

Another problem with the MVVM design pattern that’s seldom discussed is where and when the ViewModel instances should be instantiated. This problem is also frequently overlooked in discussions of similar design patterns such as MVC.

My preference is to write a ViewModel singleton that provides the main ViewModel objects from which the View can easily retrieve all other ViewModel objects as required. Often this master ViewModel object provides the command implementations so the View can support opening of documents.

However, most of the applications I’ve worked with provide a document-centric interface, usually using a tabbed workspace similar to Visual Studio. So in the ViewModel layer I want to think in terms of documents, and the documents expose one or more ViewModel objects wrapping particular Model objects. Standard WPF commands in the ViewModel layer can then use the persistence layer to retrieve the necessary objects, wrap them in ViewModel instances and create ViewModel document managers to display them.

In the sample application included with this article, the ViewModel command for creating a new Person is:

internal class OpenNewPersonCommand : ICommand {
  // Open a new person in a new window.
  public void Execute(object parameter) {
    var person = new MvvmDemo.Model.Person();
    var document = new PersonDocument(person);
    DocumentManager.Instance.ActiveDocument = document;

The ViewModel document manager referenced in the last line is a singleton that manages all open ViewModel documents. The question is, how does the collection of ViewModel documents get exposed in the View?

The built-in WPF tab control does not provide the kind of powerful multiple-document interface users have come to expect. Fortunately, third-party docking and tabbed-workspace products are available. Most of them strive to emulate the tabbed document look of Visual Studio, including the dockable tool windows, split views, Ctrl+Tab pop-up windows (with mini-document views) and more.

Unfortunately, most of these components don’t provide built-in support for the MVVM design pattern. But that’s OK, because you can easily apply the Adapter design pattern to link the ViewModel document manager to the third-party view component.

Document Manager Adapter

The adapter design shown in Figure 2 ensures that the ViewModel doesn’t require any reference to the View, so it respects the main goals of the MVVM design pattern. (However, in this case, the concept of a document is defined in the ViewModel layer rather than the Model layer because it’s purely a UI concept.)

Figure 2 Document Manager View Adapter

Figure 2 Document Manager View Adapter

The ViewModel document manager is responsible for maintaining the collection of open ViewModel documents and knowing which document is currently active. This design allows the ViewModel layer to open and close documents using the document manager, and to change the active document without any knowledge of the View. The ViewModel side of this approach is reasonably straightforward. The ViewModel classes in the sample application are shown in Figure 3.

Figure 3 The ViewModel Layer’s Document Manager and Document Classes

Figure 3 The ViewModel Layer’s Document Manager and Document Classes

The Document base class exposes several internal lifecycle methods (Activated, LostActivation and DocumentClosed) that are called by the document manager to keep the document up-to-date about what’s going on. The document also implements an INotifyPropertyChanged interface so that it can support data binding. For example, the adapter data binds the view document’s Title property to the ViewModel’s DocumentTitle property.

The most complex piece of this approach is the adapter class, and I’ve provided a working copy in the project accompanying this article. The adapter subscribes to events on the document manager and uses those events to keep the tabbed-workspace control up-to-date. For example, when the document manager indicates that a new document has been opened, the adapter receives an event, wraps the ViewModel document in whatever WPF control is required and then exposes that control in the tabbed workspace.

The adapter has one other responsibility: keeping the ViewModel document manager synchronized with the user’s actions. The adapter must therefore also listen for events from the tabbed workspace control so that when the user changes the active document or closes a document the adapter can notify the document manager.

While none of this logic is very complex, there are some caveats. There are several scenarios where the code becomes re-entrant, and this must be handled gracefully. For example, if the ViewModel uses the document manager to close a document, the adapter will receive the event from the document manager and close the physical document window in the view. This causes the tabbed workspace control to also raise a document-closing event, which the adapter will also receive, and the adapter’s event handler will, of course, notify the document manager that the document should be closed. The document has already been closed, so the document manager needs to be sympathetic enough to allow this.

The other difficulty is that the View’s adapter must be able to link a View tabbed-document control with a ViewModel Document object. The most robust solution is to use a WPF attached dependency property. The adapter declares a private attached dependency property that’s used to link the View window control to its ViewModel document instance.

In the sample project for this article, I use an open source tabbed workspace component called AvalonDock, so my attached dependency property looks like the code shown in Figure 4.

Figure 4 Linking the View Control and ViewModel Document

private static readonly DependencyProperty 
  ViewModelDocumentProperty =
  "ViewModelDocument", typeof(Document),
  typeof(DocumentManagerAdapter), null);

private static Document GetViewModelDocument(
  AvalonDock.ManagedContent viewDoc) {

  return viewDoc.GetValue(ViewModelDocumentProperty) 
    as Document;

private static void SetViewModelDocument(
  AvalonDock.ManagedContent viewDoc, Document document) {

  viewDoc.SetValue(ViewModelDocumentProperty, document);

When the adapter creates a new View window control, it sets the attached property on the new window control to the underlying ViewModel document (see Figure 5). You can also see the title data binding being configured here, and see how the adapter is configuring both the data context and the content of the View document control.

Figure 5 Setting the Attached Property

private AvalonDock.DocumentContent CreateNewViewDocument(
  Document viewModelDocument) {

  var viewDoc = new AvalonDock.DocumentContent();
  viewDoc.DataContext = viewModelDocument;
  viewDoc.Content = viewModelDocument;

  Binding titleBinding = new Binding("DocumentTitle") { 
    Source = viewModelDocument };

  viewDoc.Closing += OnUserClosingDocument;

  return viewDoc;

By setting the View document control’s content, I let WPF do the heavy lifting of figuring out how to display this particular type of ViewModel document. The actual data templates for the ViewModel documents are in a resource dictionary included by the main XAML window.

I’ve used this ViewModel document-manager approach with both WPF and Silverlight successfully. The only View layer code is the adapter, and this can be tested easily and then left alone. This approach keeps the ViewModel completely independent of the View, and I have on one occasion switched vendors for my tabbed workspace component with only minimal changes in the adapter class and absolutely no changes to the ViewModel or Model.

The ability to work with documents in the ViewModel layer feels elegant, and implementing ViewModel commands like the one I demonstrated here is easy. The ViewModel document classes also become obvious places to expose ICommand instances related to the document.

The View hooks into these commands and the beauty of the MVVM design pattern shines through. Additionally, the ViewModel document manager approach also works with the singleton approach if you need to expose data before the user has created any documents (perhaps in a collapsible tool window).

Wrap Up

The MVVM design pattern is a powerful and useful pattern, but no design pattern can solve every issue. As I’ve demonstrated here, combining the MVVM pattern and goals with other patterns, such as adapters and singletons, while also leveraging new .NET Framework 4 features, such as dynamic dispatch, can help address many common concerns around implementing the MVVM design pattern. Employing MVVM the right way makes for much more elegant and maintainable WPF and Silverlight applications. For further reading about MVVM, see Josh Smith’s article in the February 2009 issue of MSDN Magazine.

Robert McCarter is a Canadian freelance software developer, architect and entrepreneur. Read his blog at robertmccarter.wordpress.com.

Thanks to the following technical expert for reviewing this article:  Josh Smith