The Model-View-Control (MVC) pattern is more popular than ever. Microsoft has now jumped the bandwagon with its ASP.NET MVC framework. Other popular frameworks like Ruby on Rails, Django (Python) and the Spring MVC Framework (Java) all implement this popular pattern. The MVC pattern fits nicely into the request-response based nature of the web. As a request comes in, the controller makes a decision on what needs to be done, talks to the model and hands of the rendering responsibility to a view engine.

Silverlight on the other hand, even if it is running inside the, has more in common with rich client application frameworks like Windows Presentation Foundation than traditional web applications. This requires different thinking when it comes to architecting the application. In this post I’m going to talk about the View-Model-ViewModel (MVVM) pattern or as Fowler call it; the Presentation Model. As an example I’m going to re-factor my YouCard application to use this pattern.

Jon Gossman and Dan Crevier have blogged about the MVVM pattern in a WPF context, and recently Nikhil Kothari wrote an excellent post titled "ViewModel Pattern in Silverlight using Behaviors". Martin Fowler has also written about this pattern, but under a different name; the Presentation Model. What makes ViewModel so interesting for Silverlight and WPF applications is that it lets you take full advantage of the strong data binding support in Silverlight and WPF. One of the key concepts of the MVVM-pattern is to define specialized models that are tailored for a specific view (user interface). The view-model may contain special fields like IsDiscountingEnabled, or PageTitle that may be based on one or more fields form your under laying domain model. Your IsDiscountEnabled field might be based on whether or not the logged on user belongs to a specific group that have the permission to give discounts, but the actual view does not know or care about this. The view only cares about the IsDiscountEnabled field of the view-model, and is not coupled to the domain model. The view and the view-model are highly synchronized, while synchronization between the view model and the domain model only happen at certain points, like when the user hits the Apply or Save button. How you implement this synchronization between your view and your view model depends on the technology you use, but even Fowler suggests that this can be done through data binding:

Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen someday with technologies like .NET's data binding. – Martin Fowler

The synchronization code Fowler is talking about is the code where you move values from the name-textbox to the name-property on your Person object. I’m sure we’ve all written that code and can agree that it’s both boring and repetitive! Thankfully data binding has improved a lot since the .NET 1.1 and Windows Forms days, and in WPF and Silverlight data binding is a natural choice for implementing this synchronization.

YouCard Screenshot

The application I’m going to use as an example of this pattern is my YouCard application from REMIX Australia. At REMIX I talked about Silverlight 2 for designers. The focus of the talk was about using Blend 2.5 to build and design applications. The core of the application is a YouCard user control, which is data bound to a YouCardData class. This class contains functionality to retrieve data from Twitter and Flickr, and acts both as the model and the view-model for the application. It contains View-specific fields like Tweet, Name and Bio, which all are extracted from the Twitter-feed downloaded from Twitter using HTTP requests. The YouCardData class starts a timer that downloads new data from the Twitter or Flickr at given intervals. To follow good programming principles like single responsibility, I’m going to split the Twitter and Flickr functionality out to external classes. These classes will be our Model. The responsibility of these classes will be to download and parse XML into objects. The YouCardData class will become our ViewModel and will be responsible for using the Twitter and Flickr service in a way that makes sense for the View, and surface up any fields needed by the UI. Since the original design of the YouCardData class was built to highlight the strong support for data binding- and design time support in Blend 2.5, we have a good starting point for this refactoring job. The following diagram shows the current design (left) and the desired design after some refactoring:

youcardviewmodeldiagram

The first thing that needs to be done is to define some interfaces for the external services. Instead of defining an ITwitter or an IFlickr interface I have decided to use more generic names like IMicroBlog and IPhotoService. That makes more sense if we ever want to support FriendFeed, Picasa or perhaps Windows Live Photo Gallery. I am going to refactor the existing code into two concrete implementations of each interface, one for the real online service, and one mock implementation with dummy data. As I mentioned earlier this application was written as a demo for the creative track at REMIX, and to provide a good design-time experience in Blend we need to generate dummy data when the code is being consumed by the designer. If you are going to benefit from the designer-developer workflow XAML enables, you need to start thinking about how your code behaves inside the design tool. In the current implementation dummy data is provided in the YouCardData class through an if-statement in the constructor checking if we’re running inside Blend or not. If we’re running inside Blend the YouCardData class will use a mock implementation of the Twitter and Flickr services. If it’s running inside the browser it will start a timer and begin to download data from Twitter and Flickr using the real implementations. The important part of the YouCardData constructor now looks something like this:

 Code sample 1

You might notice that this code screams for some dependency injection, and that is exactly what I’m going to cover in my next blog post. We check the type of the current application object. Blend provides its own application object, while actually running the application gives us our own application object.

The next piece of the application that needs some refactoring is the main user interface. By that I mean everything around the cards. Today the application contains one text box where you enter in a Twitter-username, and an add-button to add a new card. In the click-event handler we instantiate a new YouCard user control and add it to a stack panel. We also hook up an event handler listening for a close-event fired by the YouCard control. If the event fires we remove it from the stack panel. This approach is bad for a number of reasons. The main problem is that we are building too much behavior and logic into the view (the code behind of the XAML page). For instance the designer doesn’t have the freedom to change from a stack panel to a flow panel without changing the code. It’s also hard to unit test the code since much of the application logic is bound to specific UI-controls and UI-events.

To solve this problem we create a new view-model that contains an observable collection of YouCardData objects called Users. This collection is bound to an items presenter control, which uses the YouCard user control as its data template.

Code sample 2

With both pieces of UI bound to view-models we have now control over how we display data. But this is just half the story of an application. We also need a way to interact with the view-model as the user adds or removes cards.

YouCard interaction photo

In the YouCard application there are two points of interaction that affects the view-models, the textbox and button to add a new user, and the red button to remove a card from the list. The user can type in a username and hit enter, or click the add button to add a new item to the Users collection. The add button should only be enabled if the user name is valid. When the user clicks the close button of a card we need to remove the item from the collection in the view-model. In this case it involves communicating from one view to the view-model of a different view. The YouCard user control needs to tell the view-model for the main UI to remove itself from the list.

The most obvious solution could be to add a click event listener on the add button, and call methods on the view-model to add a new users. We could listen to the text changed event of the textbox to validate the input and enable/disable the textbox based on the text. We could also add an event to the YouCard control that gets fired when the user clicks the red button. The main view could listen to this event, and remove the corresponding card from its view-model. The problem with this solution is again that we will be baking logic and behavior into the views, which should be owned by the designer. It also makes it harder to unit test things like the validation rules, and that any users added or removed is persisted to the local machine using isolated storage (the application stores the list of cards you have added).

To solve the interaction between the view and view-model we’re going to apply the command pattern. The command pattern enables us to encapsulate an action into a command object. The command object normally contains an execute method, a name and description, and some information about whether or not the command is enabled. A single command can be attached to multiple UI elements. You might want to invoke the open-file-command from a button, a keyboard shortcut and a menu item. WPF have built-in support for Commands, but this is not included in Silverlight 2.

Nikhil introduces some really cool ideas on how to enable command-like functionality through Silverlight behaviors. This is the same concept used to extend ASP.NET controls with AJAX behaviors. In his first ViewModel post Nikhil uses the following syntax to invoke commands from XAML:

Code sample 3

Using an attached property he adds a behavior to the button which invokes the Search-method on the view-model, passing in the text property of the search textbox as the parameter. In a follow-up post Nikhil shows how he managed to get the syntax even more compact using the Dynamic Language Runtime:

Code sample 4

The cool thing about this approach is that you can write any dynamic language expression into the attached click event. This can include method invocations and getting parameters from other elements on the page. This gives you amazing flexibility to link your view to your view-model. The problem with this approach is that you get a dependency to the dynamic language runtime, which will affect the size of your Silverlight application. But more importantly for me it breaks design time support in Blend 2.5, so we need to find an alternative approach.

I decided to use a more classic command pattern implementation found in the "Silverlight Extensions" project on CodePlex. The project contains controls, helper classes, extension methods and more. Since we’re only interested in the command pattern implementation I decided to move those classes into the YouCard project. The XAML for our textbox and button now looks like this:

Code sample 5

The textbox is bound to a Username-property on the view-model. Both controls invoke the AddCard-command, using the username of the view-model as the command parameter.

The commands are defined like this:

Code sample 6

The static Commands-class holds a reference to all the commands available in the application. When instantiating a new Command-object it gets added to a static dictionary on the Command-object, caching any command object created by the application. When using the CommandService-attribute from XAML, the CommandService class will link the UI-element with the correct command using a CommandSubscription class. When the user clicks the Add User-button, or hit enter in the textbox, the CommandSubscription-class will listen for the correct UI-event and trigger the Executed-event for the correct Command-object. Any class that wants to take action when this command executes simply listens to the Executed-event of the Command object. In our case we want to handle adding or removing cards in the view-model class:

Code sample 7

Also worth mentioning is the enabling/disabling of the Add User-button. This is done through data binding the IsEnabled-property of the button to an IsAddEnabled-property of the view-model. The IsAddEnabled-property looks like this:

mvvp-code8

The textbox is bound to the Username-property, which will trigger the PropertyChanged-event for the IsAddEnabled-property. In the getter of the property we apply the validation rules that decide whether or not the button should be enabled.

Hopefully this post gives you another example of how the Model-View-ViewModel can help you keep as much code as possible out of your user interface. The strong data binding support in WPF and Silverlight makes this pattern particularly interesting, as you don’t have to worry about synchronizing your view and your view-model through hand written code. Using commands you can separate the actions of your application from the concrete UI-element invoking it. This gives your designers the freedom to choose which UI elements to use to invoke different actions in your application. Best of all, we’ve been able to do all this without breaking design-time support in Blend. In my next post we’ll continue on improving the YouCard application making it more testable by introducing dependency injection.

youcardinblend

Sunday, July 20, 2008 4:36:10 AM (AUS Eastern Standard Time, UTC+10:00)
Nice post Jonas. I have used the MVVM pattern a bit, and it's a great way to separate the model from the Gui. I tend to lean a bit against MVC because of the "tricky" bit of updating the View against the Model when using MVVM. MVC
is better if you can use the model directly, but when you need to change the data before showing it in the view, MVVM is the pattern to use. Do you have any experience with MVC and Silverlight/WPF?
Sunday, July 20, 2008 4:57:54 PM (AUS Eastern Standard Time, UTC+10:00)
Hi Pål, and thanks! :)
I haven't done anything with "classic" MVC in WPF or Silverlight. And I'm not sure if classic MVC is what you want. This is" something Fowler also points out in his GUI Architecture essay:

"...I've lost count of the times I've seen something described as MVC which turned out to be nothing like it. Frankly a lot of the reason for this is that parts of classic MVC don't really make sense for rich clients these days. But for the moment we'll take a look at its origins..." http://martinfowler.com/eaaDev/uiArchs.html

If you are going to use a classic MVC pattern in Silverlight/WPF, you're basically handing the event handling off to an external class. One way to do it could be:

public void MyView()
{
this.Controller = new MyViewController(this);
}

And the MyViewController would listen to the UI-events triggered by each UI-control in the MyView class. This is how the original MVC pattern came about in SmallTalk, where you would have one controller for each UI component on the screen, something Fowler discuss in his post. This article explores a classic MVC approach in WPF: http://dotnetaddict.dotnetdevelopersjournal.com/exploring_the_mvc_pattern_in_wpf.htm.

The problem is that your controller is tightly coupled to your view and its UI components. In web applications this isn’t a problem, as all your screen state is transmitted in one big bulk back to the server as a form-POST. The controller doesn’t care which UI-controls where used to fill in the values, it only cares about the form data. In WPF you have to read and write values directly to the UI components.

For more modern UI frameworks other architectures have turned out more popular. I guess the most commonly used WPF/Silverlight pattern is the MVP, which is supported by frameworks like Composite WPF, CAB etc.

If you build good view-models you might not need the presenter, as all data is surfaced from the model to the view-model, and displayed using data templates. Interaction is handled through commands. For larger/more complex applications the MVP pattern and some framework like Composite WPF (aka Prism) might be a better pick.

All in all I think pretty much any WPF pattern applies to Silverlight, as they share all the same core features and architecture, and there is already a “Prism for Silverlight” implementation supporting composite Silverlight applications.


Friday, August 08, 2008 12:50:51 PM (AUS Eastern Standard Time, UTC+10:00)
Hi Jonas,

I'm working in a team of a WPF project and we're exploring the advantages of MVP in our project. Our main goal is to have our application logic easily-compatible with other UI technologies like Silverlight and ASP.net for Web or any other "view" that we would want to use.

Do you think that M-V-VM (Presentation model) should be used in this scenario?

Thanks in advance,

[]s! Rodrigo Ratan
Rodrigo Ratan
Friday, August 08, 2008 1:21:17 PM (AUS Eastern Standard Time, UTC+10:00)
Hi Rodrigo,
The Model-View-ViewModel or Presentation Model as Fowler calls it is in my eyes a special case of the Model-View-Presenter pattern focusing even more on the data binding and commands. When using the MVP pattern your presenter communicates with the view through interfaces. The view creates a presenter and passes in a reference to the view interface. For instance you may have an ICustomerView, a CustomerPresenter and a concrete WebCustomerView. This would look something like this:

public interface ICustomerView
{
string Name { get; set; }
}

public class CustomerPresenter
{
private ICustomerView view;

public CustomerPresenter(ICustomerView view)
{
this.view = view;
}

public void LoadCustomer()
{
view.Name = "My Customer!";
}

public void SaveCustomer()
{
string value = view.Name;
// Save to DB
}
}

public class WebCustomerView : ICustomerView
{
private CustomerPresenter presenter;

public string Name
{
get { return txtName.Text; }
set { txtName.Text = value; }
}

public WebCustomerView()
{
presenter = new CustomerPresenter(this);
}

public void Page_Load(object sender, EventArgs e)
{
presenter.LoadCustomer();
}

public void btnSave_Click(object sender, EventArgs e)
{
presenter.SaveCustomer();
}
}

As you can see the concrete view implementation listen to UI-events and call methods on the presenter. The presenter then talks to the Model (database, web service or what ever) and gets thata and updates the view. The bennefit of this pattern is that it’s “UI agnostic”, meaning that the thing that couples your presenter to your View is the View-interface. So the MVP framework would work nicely in both Windows Forms, WPF, Silverlight and APS.NET applications...

The draw-back is that you need modre code-behind in your XAML files to implement the IView-interface. WPF and Silverlight has fantastic databinding support, and patterns like ViewModel/PresentationModel really lets you take advantage of that. The Command-Patern lets you lously couple UI-events (like buttons beeing pressed) with the subscriber (the ViewModel). The benefit of having slim (or no) code-behind your XAML files is that it makes it easier for designers to be creative and really “own” the UI experience. Once you have alot of code you’re view interface implementation is bound to the concrete UI widgets (textboxes, checkboxes etc), and changing the UI in XAML would require to change some C# code as well.

If you’re about to start on a new WPF project I would recommend checking out Prism (now known as Composite WPF - http://www.codeplex.com/CompositeWPF).
For an easy-to-follow introduction to MVP check out http://msdn.microsoft.com/en-gb/magazine/cc188690.aspx - It’s using Windows Forms and ASP.NET for its samples.
Friday, October 03, 2008 3:12:16 AM (AUS Eastern Standard Time, UTC+10:00)
Jonas

I've had a look at this code. Where exactly is the PageViewModel() constructor called?

thanks
Matt
Friday, October 03, 2008 7:11:52 AM (AUS Eastern Standard Time, UTC+10:00)
Hi Matt,

That's the beauty if Inversion of Control and Dependency Injection.

I set up the constructor and list all dependencies the class need to be instantiated. I den configure the Ninject container to stay which implementation I want to use for each interface/class.

So I say that for the IBlogService I want to use Twitter, and for the IphotoService I want to use Flickr. This is configured through the configuration code in Module Configuration.

The PageViewModel is exposed as a property on the ServiceLocator class. This is so that I can access it through declerative data binding.

The get-er for the property has code that looks like this:

kernel.Get<PageViewModel>();

That line of code says: "Hey you IoC container, I need a PageViewModel. You go figure out how to instansiate, and pass in the correct dependencies".

The IoC container will find the constructor marked with [Ninject], and it will see that it needs one IBlogService and one IPhotoService. So before It can call the constructor it needs to work out these two implementations. So it starts looking: what should I use for this interface? It figures out that I've configured it to use Twitter and Flickr, and calls the constructor on these to classes. Once it was two instances of the IBlogService and the IPhotoService It can now invoke the consturtor of the PageViewModel.

Hope this explains it :)

I know this can be tricky at first, but it's a really powerful technique to build decoupled components.


Friday, October 03, 2008 9:32:14 AM (AUS Eastern Standard Time, UTC+10:00)
Jonas,

Thanks for your response and explanantion. I have one other question:

Say the ObservableCollection<CardViewModel> Users collection was going to be updated from another view. Eg. The "add user" text box was actually in a seperate view. In the VMMV model how would another VM update this collection and trigger the users to get updated in PageViewModel?

thanks
Matt
Monday, October 06, 2008 2:22:40 PM (AUS Eastern Daylight Time, UTC+11:00)
Hi Matt,

You have a couple of options. The AddUser button triggers a Command, and any ViewModel can listen to the Executed event of that command. That's the benefit of the Command pattern. You loose couple the invoker and the handler of an command.

So, some button in View-A triggers the Command NewUser
The ViewModel-B listens tho the executed of the NewUser command, and does what ever it need to add a new user.

In this scenario the requirement is that all information is packaged into the NewUser Command Parameter.

I also recommend checking out the Communication section in the Composite WPF documentation. It covers how to do cross-module communication: http://msdn.microsoft.com/en-us/library/cc707836.aspx


Saturday, October 25, 2008 2:49:47 AM (AUS Eastern Daylight Time, UTC+11:00)
In looking at the sample code that you provide here, it appears that you're using a different version of NInject from whats available on their web site as the latest stable release. Are you using a pre-release version that has some ExtensionMethod compatibility or something like that? I've been using NInject in a Silverlight project, and it was working great until I attempted to implement the Command pattern that you have in your solution. When I imported the files required to implement that pattern and compiled, I'm getting errors about conflicting ExtensionAttribute objects. Got any ideas?
Sunday, October 26, 2008 7:15:46 AM (AUS Eastern Daylight Time, UTC+11:00)
@Bob: Yes - Ninject is such a "small" project that I just pull it directly from their SVN repository. That way I always got the most current code. There was some issues around Silverlight and Beta 2 at the time I wrote this post.

I don't know what the most current stable release of Ninject is, but I hope/assume there is a new release targeting the Silverlight 2 RTW runtime around the corner.

I'm not sure why the command pattern implementation is conflicting with the ExtensionAttribute.

I'm currently at the PDC, so won't have time to look into this until later. I plan to do a post about an improved implementation of the Command pattern based on the Prism project.

Cheers,
Jonas
Tuesday, October 28, 2008 3:03:55 PM (AUS Eastern Daylight Time, UTC+11:00)
I've been studying the MVVM pattern and really like you post.

I have a question that I hope you can help with.

Your ViewModel provides change notification to the View.

How does the Model provide change notification to the ViewModel and then up to the View.

Example: Model has a property that gets set on certain conditions within the Model. If I was not using MVVM, I would bind the UI to the property in question, all is well.

Now that MVVM is in the picture, what technique can I use in my Model to provide notification to the ViewModel? Do I need to implement INotifyPropertyChanged in the Model also?

Thank you!!

Cheers,

Karl
Friday, November 14, 2008 4:54:30 AM (AUS Eastern Daylight Time, UTC+11:00)
This is my Korean translation. Thank you for your nice post.

http://wafe.kr/entry/Silverlight-Model-View-ViewModel-Pattern-Translation-1
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

<November 2008>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456
www.flickr.com
This is a Flickr badge showing public photos from follesoe. Make your own badge here.