Model-View-ViewModel Pattern for WPF: Yet another approach
A few days back, I posted an example here of implementing Model-View-Controller in a WPF scenario. On a side note, WPF specialist Josh Smith posted his own rendition here, which is also a very nice example and a more humorous choice of program.
A quick redux:
I was originally bamboozled by the two-way databinding features of WPF. I architected a GUI that was directly bound to my business objects.
This was a bad idea for me. Why? Because my business objects do not support any form of invalid state. As the user edits the screen, he/she is directly editing a business object.
The object is in a transitional state at this point. It should be OK to allow invalidity as the user edits, but my business object will not allow invalid values, so validation and user interactivity breaks down in this approach.
I need something that stands between the GUI and the BOs. I know! Lets pull out the classic Model-View-Controller Pattern!
Now I can allow the user to edit the UI as they please. When the user clicks some sort of an "Apply" or "OK" button, an event is sent to the controller, where an attempt is made to perform some of the user's changes. At the very least, validation can occur at this point; the business object will throw any exceptions and they can be caught, logged, and displayed, put on the evening news, and troops will be deployed to Norway. If there are no exceptions, the business logic is successfully performed, and the view's bindings are updated to reflect the changes in the model. This is a popular design with the web-based guys, since their views have no state.
I wasn't happy with this. Why? I'm not working web pages right now; I want two-way databinding. I have to write plumbing code to send data from the GUI to the controller? I have to write plumbing code to send changes from the model to the GUI? Wasn't the whole point of WPF databinding to get rid of this plumbing code?
The Model-View-ViewModel Pattern: Binding to Facsimile Objects
I want to dynamically bind to something that doesn't really support dynamic binding. What to do? The MVVM approach is a very attractive compromise between two-way databinding and rigid model integrity!
Before I begin, I owe references to the masters and creators of this design:

I'll break it down into the key elements:
A few key pieces here:
Observations along the way:
A quick redux:
I was originally bamboozled by the two-way databinding features of WPF. I architected a GUI that was directly bound to my business objects.
This was a bad idea for me. Why? Because my business objects do not support any form of invalid state. As the user edits the screen, he/she is directly editing a business object.The object is in a transitional state at this point. It should be OK to allow invalidity as the user edits, but my business object will not allow invalid values, so validation and user interactivity breaks down in this approach.
I need something that stands between the GUI and the BOs. I know! Lets pull out the classic Model-View-Controller Pattern!
Now I can allow the user to edit the UI as they please. When the user clicks some sort of an "Apply" or "OK" button, an event is sent to the controller, where an attempt is made to perform some of the user's changes. At the very least, validation can occur at this point; the business object will throw any exceptions and they can be caught, logged, and displayed, put on the evening news, and troops will be deployed to Norway. If there are no exceptions, the business logic is successfully performed, and the view's bindings are updated to reflect the changes in the model. This is a popular design with the web-based guys, since their views have no state.I wasn't happy with this. Why? I'm not working web pages right now; I want two-way databinding. I have to write plumbing code to send data from the GUI to the controller? I have to write plumbing code to send changes from the model to the GUI? Wasn't the whole point of WPF databinding to get rid of this plumbing code?
The Model-View-ViewModel Pattern: Binding to Facsimile Objects
I want to dynamically bind to something that doesn't really support dynamic binding. What to do? The MVVM approach is a very attractive compromise between two-way databinding and rigid model integrity!
Before I begin, I owe references to the masters and creators of this design:
- Dan Crevier has the complete and unabridged version of MVVM. Go read straight from the source to get the full picture. The guys is very sharp, and savvy with WPF implementation details that I may never fully understand.

I'll break it down into the key elements:
- Forget the controller, you wont be needing it here
- You can keep the "IView" interface from the previous example, but they are much less useful, since we will not be mocking a view in the unit tests any more. I threw them away to keep things simple.
- The Model objects don't change.
- The ViewModel is a "made for UI" object that represents the Business Object.
- The UI supports direct, two-way intimate binding with the ViewModel
- The ViewModel supports invalid states. It can easily implement IDataErrorInfo here
- When the user "commits" the edits, the ViewModel attempts to "update" the model object that it is representing.
/// <summary>
/// A view model is a facsimile of a business object that is safe for databinding and invalidation
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class ViewModelBase<T> : IDataErrorInfo where T : BusinessObject
{
/// <summary>
/// The model that the ViewModel is representing
/// </summary>
protected T Model
{
get;
set;
}
/// <summary>
/// ViewModels can represent new Models that havent been created yet.
/// If the model is null, then a "construction" will occur uppon the call to ApplyChanges
/// </summary>
protected bool IsNewModelInstance
{
get { return Model == null; }
}
/// <summary>
/// Setting up for a new model instance
/// </summary>
public ViewModelBase()
{
Model = null;
}
/// <summary>
/// setting up for editing an existing model
/// </summary>
/// <param name="model"></param>
public ViewModelBase(T model)
{
Model = model;
}
/// <summary>
/// Attempt to create or edit the underlying business object
/// </summary>
public void ApplyChanges()
{
try
{
if (IsNewModelInstance)
CreateModel();
else
ApplyToModel();
UpdateViewModelFromBusinessObject();
}
catch(Exception e)
{
UpdateViewModelFromBusinessObject();
throw e;
}
}
/// <summary>
/// edit the underlying model
/// </summary>
protected abstract void ApplyToModel();
/// <summary>
/// create the underlying model
/// </summary>
protected abstract void CreateModel();
/// <summary>
/// Any changes to the model should be reflected in the ViewModel
/// </summary>
protected abstract void UpdateViewModelFromBusinessObject();
#region IDataErrorInfo Members
///<summary>
///Gets the error message for the property with the given name.
///</summary>
///
///<returns>
///The error message for the property. The default is an empty string ("").
///</returns>
///
///<param name="columnName">The name of the property whose error message to get. </param>
public abstract string this[string columnName] { get; }
///<summary>
///Gets an error message indicating what is wrong with this object.
///</summary>
///
///<returns>
///An error message indicating what is wrong with this object. The default is an empty string ("").
///</returns>
///
public abstract string Error { get; }
#endregion
}
A few key pieces here:
- A ViewModel can be used to construct a new business object, or it can be used to edit existing ones.
- A ViewModel exposes its own copy of public properties of the inner object, and they can indeed be as invalid and cockeyed as the user pleases.
- When the user clicks "Apply", the ApplyChanges method will be called, which will either attempt to construct a new BO or edit an existing BO using the properties from the ViewModel. Exceptions may be thrown by the BO, and they will be caught and displayed in the normal fashion.
Observations along the way:
- As you allow the user to do more and more before clicking apply, the chances of exceptions and validation problems increases. All the better reason to implement IDataErrorInfo, I suppose.
- I am still not happy with the IDataErrorInfo interface. The ViewModel has validation, the business objects have validation, I need to find a way to reuse the validation from the BOs and not rewrite this!
- As you allow the user to do more and more before clicking apply, the Apply() method of the ViewModel object will become more complicated as it tries to synchronize the business objects with its own state. These are a lot of Moving Parts.
- The ViewModel and the Model contain the bulk of the intelligence, and they are very easy to isolate and test.
- Josh Smith and others tell me that the CSLA framework handles this tie between the GUI and the BO in a graceful manner. I want to find the best solution, I will be researching here next.


20 Comments:
Another stellar post! This is a great usage of MVVM. As for the concern about not duplicating validation logic across your Model and ViewModel, perhaps using the CSLA notion of validation rule objects would be useful here...
Thanks,
Josh Smith
Indeed I was in the middle of a CSLA video demo this very moment...
Pretty impressive to say the least!
I think if the ViewModel were to provide rundimentary validation rules when the view is constructed, the problem of validation becomes less and less significant when the user selects the apply button. I'm suggest the Model / ViewModel should be allowed to do both, validate on user input as well as on apply
Have you looked at Enterprise Library 3.1 for Validation (and Policy Injection)?
Martin Bennedik has done some great work creating a ValidationProvider for WPF which integrates with the existing Enterprise Library validation framework(s).
http://www.bennedik.de/2007/05/update-of-wpf-integration-for.html
Adam, I apologize for not getting back to you sooner, I've been under the gun in the last month (hence the lack of blogging activity).
I DID look in to the validation features of the enterprise library, and I remember appreciating the syntax (much like postsharp-validation). I read some of your blog when I was trying to learn how it applies to WPF. I ultimately rejected it for my purposes, but I cannot remember why... Was it more complex than postsharp? Was it because it does not throw exceptions when invalid values are passed in? Are there implications where my business objects could be in an invalid state? I am interested in discussing this further, but I cannot remember what specific facet about Enterprise lib that turned me off.
This is exactly what I have been looking for. Thank you.
Rob FireGarden
BTW, I have found that in practice, when you are creating new model instances, I found it is nice to construct a "Default" model for the ViewModel, if possible.
An analogy in windows would be like windows explorer when you create a new empty text document before you start the editor.
Hi Pete,
thanks for your excelent post about M-V-VM pattern with a so-easy-to-understand example. I am anlyzing your code and have learnt a lot from that.
Greetings,
Quang.
Hi Pete and others,
I have one problem relating to this pattern:
In my current project using C#, WPF
technology, I have a quite big "project object" with extensive information
like: project id, project title, list of workers who work on that
project, privileges that the current user can do on the project, an XML
string representing the project structure etc.
Now based on this project object I have different windows to display parts of its in different manner:
- On the left hand side, a project structure tree in a treeview.
- When the user click on a tree item, an editor is displayed showing the coresponding detailed information to that node. A tree node can be either: project root, package or work item which is model with the well-known composite pattern.
My question is: should I have only one "big" ProjectViewModel for all different displays or it is better to have a "smaller" ViewModel for each kind of displays (one ViewModel for project structure, one for each kind of tree nodes as stated above etc.)
I would love to hear your opinions about this.
This is a special case of the general situations where we have one big business object (like project in my case) with different visual displays (project tree, work item view etc. in my case).
Great post! I have the same problem and I think that MVVM is a good solution.
I tried your code but I noticed that validators on ViewModelObject don't work, because there isn't ValidateOnDataErrors=true on XAML and the properties name "Name" and "Content" don't exist. I changed the names in "BlogEntryName" and "BlogEntryContent" and now it works. Is it right or not?
I also notice that if I change or remove validators on PostSharp, they don't work, is it correct?
@quang tran minh--
I think that your situation calls for a unique scenario: you have what is often known as a "master-detail" scenario, where the treeview on the left is a master view, and the pane on the right represents a detailed view of some selection on the master. I would recommend a MVC approach for the master information, and a MVVM (and possibly user controls) approach for the details pane
@guiseppe --Thank you for the update on my coe I havent had a chance to review this in better detail since I posted it.
Its true, my objects currently throw exceptions at button click time, not before. One of the cool features of WPF is simple real-time validation, and I should have leveraged this in my example. In my spare time (hahahahahhaha) I'm going to make another blog post explaining this scenario in even more detail.
What I'm learning is that so many people are running in to this situation with WPF... have you taken a look at this yet?
http://devlicio.us/blogs/rob_eisenberg/archive/2008/01/07/introducing-caliburn-an-mvc-mvp-wpf-framework.aspx
Hi Pete, my scenario is this:
I have in a page a listview with a list of items and under the item detail. I want create, modify and delete items. This scenario is simple, but with WPF if my collection extend ObservableCollection and my Object INotifyPropertyChanged I have to manage binding. So if I modify an Item that is binding with BO, and I decide to undo the operation my BO remain dirty and also the listview. I think that the better solution to use the WPF features is to adapt a MVVM Pattern or bind the detail with a copy of the selected item of listview(for EDIT) or new instance of my BO (for CREATE).
What I am hearing is: a UI with a master-detail view.
The master view has an observable collection of detail objects.
The master view is directly bound to the master object.
The detail view is directly bound to the detail object.
Since everything is directly bound, changes go directly to the objects.
OK. When you create a new "detail" object, give it valid default values, and add it to the master object. (You can see an example of similar behavior on your desktop, when you create a new text file, it creates the file, gives it a default name, and then allows you to edit that name after the file is created)
The detail view needs to be directly bound to a ViewModel that represents the detail object. If your detail object is not very complicated, then your ViewModel could simply be a clone of the of the model, I suppose. When the user clicks "apply", the clone will attempt to push its values into the model object. This design is very common and it is one of the key concepts of the CSLA. If youre not familiar with Rocky Lhotka's CSLA, you should take a look, its not elegant, but it is certainly proven effective.
I want to implement MVVM for my scenario. The only doubt is that I have to implement in 2 point validators. The question is, is not enough to implemnt validators on VMOB?Why I have to implement validation also on BO?
Have you ever seen this kind of validation?
http://www.bennedik.de/2007/04/wpf-integration-for-validation.html
http://www.codeplex.com/entlibcontrib/Wiki/View.aspx?title=Standalone%20Validation%20Block
Yes I am familiar with the VAB.
The situation I am hearing is that:
1) you want to validate on the UI level as the user enters data.
2) you want to validate on the object level.
On the UI level, if your object is invalid, it is visually flagged. On the object level this raises an exception.
You dont want to write the same validation code for both the UI and the object.
At this point what you do is very specific to your design. of your business objects allow invalid data, then they can implement IDataErrorInfo, and report anything invalid. If your business objects dont ever allow any invalid data, then you will need to extract the common validation logic shared by the ViewModel and the Model into a new class. Much like the strategy pattern, where the strategy would be the validation logic.
come to think of it, I think the strategy pattern is the core concept behind the VAB!
No I want to validate only one time!
You use IDataErrorInfo and PostSharp.
There is a possibility to declare the validation rule only on the Business Object?
If a implent the validator on ViewModelObject, is not enough? If the user input data aren't valid, the businnes object does not exist.
Is it right?
That is certainly one way of doing it.
Good post but I'm wondering if this is fundamentally different from the presentation model pattern:
http://martinfowler.com/eaaDev/PresentationModel.html
Great post, it helped me a lot. Thank you!
Post a Comment
<< Home