Tuesday, June 1, 2010

how to build an outlook style application with prism v2 – Part 2

how to build an outlook style application with prism v2 – Part 2: "

A while ago, I put an example application on my blog on how to build an outlook style application.

The last couple of weeks, I’ve been working on a new version of this app. I’ve done some bugfixes, but also included support for opening use cases in a popup window. It’s turning out to be quite an advanced demo of what’s possible with Prism. But while I’m playing with it, I can’t help but be amazed with the things I can push Prism into doing :)

<Outlook style app>

You will need the following references to make the solution work:

So there are a couple of things I didn’t explain in my previous blog:

  • How to do ViewModel first development?

  • How to open a Use Case in a popup?

  • Why I’m using ObservableObject in my ViewModels?

So here goes:

ViewModel first development

I’m a big van of ViewModel first development. So what does that mean?

  1. I create my ViewModels before i create my Views. This allows me to create testable viewmodels that absolutely don’t rely on any visual aspects.

  2. My application code programs against ViewModels, not Views. Most of my code doesn’t need to know about the views. Only when a ViewModel needs to be displayed should you load up the view to display it.

There are a couple of big advantages to this approach:

  • You can easily unit test your UI logic, without relying on visual elements.

  • I can easily reskin my app.

  • You don’t have to forward data from your views to your view models. This is something I have always found annoying with a View First approach. For example, if you have a view that displays a person and needs a PersonID to do it. With view first, your code has to talk to the view. So the view needs a PersonID property. But actually, the logic of your view needs that PersonID, so it needs to be forwarded to your ViewModel. Annoying, tedious, error prone!!!

I wanted to be able to put ViewModels into my regions and to have some code that would provide the visualization onto it. So the code I want to be able to write is:

// 1: Setup visualizations (typically in Module.Initialize)
// Whenever an EmailMainViewModel is displayed, visualize it with an EmailMainView
modelVisualizationRegistry.Register<EmailMainViewModel, EmailMainView>();

// 2: Add ViewModels to region (view discovery, view injection or any other method)
region.Add(new EmailMainViewModel());

ViewModel First internals

If you’re interested in how I built the ViewModel First code? here it is:


The first step into creating the view model first appraoch was to create a ModelVisualizer class. The reason for this was: 'The prism region adapters will put the content of the regions directly into the control that hosts the region (for example, a contentcontrol). There is no extensionpoint to sit in between that.

So I created something that I could put in a region, that would hold BOTH the View and the ViewModel. It would be the glue between the view and the viewmodel and:

  • Set the View as the content in the Visual Tree.

  • Set the ViewModel as the datacontext for the View.

  • Forward common information between the ViewModel and the View (such as the RegionContext or the IsActive values)

The following diagram explains my ModelVisualizer.


The ModelVisualizer IS a ContentControl. So it can be placed inside the Visual Tree. It will set the View as the content. It will also set the ViewModel as the datacontext of the view (so the view can bind to all the information in the ViewModel). Lastly, the IModelVisualizer implements the IRegionContextAware and IActiveAware interfaces, and will synchronize these interfaces with the View and ViewModel if they implement the interfaces.

Visualizing Region

The ModelVisualizer worked great. However, it demanded that all my code knew about the ModelVisualizer. I didn’t want to do that, because I wanted to make it implicit. There were some issues with that though, because due to the current implementation the region adapters, I didn’t have an extension point to create my visualizations implicitly. I couldn’t change the type of region that was created by adapters and I couldn’t change how the adapters set the content of the region to the hostcontrol. But I solved that with a little trick, that I call my VisualizingRegion.

The trick was: while I couldn’t change what type of region was being created, I could control what type of region was registered to the RegionManager (because there is a regionbehavior that does the registration. So I just wrapped the Region that was created by the regionadapters in my own region (the visualizing region) and registered my own visualizing region to the regionmanager.

The only way a consumer can get access to the Region is through the RegionManager, so that solved the problem :)

Easier Solution to region context

In Prism V2, we introduced the concept of RegionContext. The RegionContext is a way that a view that hosts a region can share some of it’s information with any childviews that are loaded into it’s region. While I really liked the concept of RegionContext, I didn’t really like the implementation of it.

So I created the IRegionContextAware interface. It has one property (the regioncontext as an ObservableObject) and the RegionContextAwareRegionBehavior that would sync the context of the region with the RegionContextAware properties.

Opening a Use Case (or ViewModel) in a popup

One thing I thought was an interesting challenge was opening a viewmodel in a (non modal) popup. So why would this be challenging:

  • You can have many instances of the same popup open at the same time.

  • Viewmodels shouldn’t know if they are opened in the main window (perhaps in several tabs) or in a popup. This should be decided by the designer, preferably in XAML.

The code I wanted to be able to write is:

   1: // Create an UseCase to write new email messages
   2: NewEmailUseCase newEmailUseCase = ApplicationModel.CreateObjectInScopedRegionManager<NewEmailUseCase>();
   4: // Add some data to the Email message use case (in this case, a blank new email)
   5: newEmailUseCase.Message = new EmailMessage();
   7: // Show the email (in a popup, but the consumer doesn't know that)
   8: ApplicationModel.ShowUseCase(newEmailUseCase);

The problem with opening several instances of the same popup is: Regions are identified by name in the regionmanager. If you have several popups of the same type open, each popup needs it’s own RegionManager, or else the region names will collide. In my scenario, I decided that the Popup has most of the same region names as the main shell. That way, any ViewModel or use case could be loaded in either the popup or the main window.

Creating use cases in a scoped regionmanager

Ok, so i need to create a scoped regionmanager. That’s not to hard, just do: RegionManager.CreateRegionManager() and you have one. However, I wanted the consuming code NOT to have to think about this. It should be blissfully ignorant about the fact that it’s in a scoped regionmanager or not.

Since all most of my objects are created by a DI Container, and it injects all of the dependencies to my object, I decided to use that to solve this problem. So I created a scoped Container and registered the scoped regionmanager with that. Then I created my use case from the newly created scoped container, and if it needs a regionmanager, it would automatically get the scoped regionmanager. Pretty neat huh.

So schematic, that looks like this:


So when the use case (in green) get’s created, it and it’s dependencies would get the scoped regionmanager injected. Without knowing about the scoped containers or scoped regionmanager.

Adding use cases to popups

Adding the use case to a popup (in the application model) works like this:


  1. Create the use case.
    Your code creates a new use case instance, for example new NewEmailUseCase(); The application model has a method to create a use case within a new RegionManager scope (as described before).

  2. Show use case.
    Your code calls the Application model to show the use case.

  3. Add to region.
    The application model (which is logic) doesn’t even know if the use case is displayed in a popup or not. It just adds the use case to a region. The region itself is defined in the Shell.XAML.

  4. Visualize the Use case
    Just as a visualization (view) can be registered for ViewModels, i’ve also registered a visualization for Use Cases. In this case, I’ve registered a window (called Popup.XAML) as visualization.

  5. Show /Close the popup on activate.
    Now that the visualization is there, I had to create some code to show and close the popup. I decided that, if i Activate() the use case, the popup should be displayed. If I deactivate Use case, the popup should be closed and the use case should be removed from the region. This functionality I put in a RegionBehavior, because it can easily monitor if something is added or removed from a region.

  6. Assign scoped region manager to the popup
    Lastly, the popup window needs to know the RegionManager that the Use Case wants to use. So I’ve created the IRegionManagerAware interface. If a usecase implements that interface, anything that’s placed inside the region will get this region manager assigned.

As you can see, there are quite a lot of moving bits for showing a use case into a popup. Of course, it would have been A LOT easier to give ‘your code’ (an other use case or something) the knowledge that a view can be opened in popup.

ObservableObject for easier binding

If you look at my viewmodels, you’ll see that I make use of the ObservableObject a LOT. It’s a very simple object, one that just takes a type and wraps it in a INotifyPropertyChanged. The nice thing about this is, that I don’t have to add any INotifyPropertyChanged code in my ViewModels anymore. That makes it soooo much easier to do 2 way databinding in WPF.

The only problem is, that to get to the value, you often have to do: viewModel.MyProperty.Value to get to the actual value of MyProperty. But I thought that’s worth it since now I don’t have to write INotifyPropertyChanged code for my properties anymore.


Like I mentioned, before, this outlook style app has become quite an advanced demo of what’s possible with Prism. But I hope it gives you some idea’s on what’s possible with it. I’m also in the process of creating a video walkthrough of this application. But I’ll let you know when that’s done!

Keep practicing!



If you get an System.Threading.SynchronizationLockException from Unity: Don’t worry! I had turned on ‘break on all exceptions’ so the debugger is also breaking on these handled exceptions. Just continue and the app will run fine, or change that debug setting.


how do i do… With the Model-View-ViewModel pattern

how do i do… With the Model-View-ViewModel pattern: "

While building the Composite Application Guidance for WPF and Silverlight (AKA Prism V2), we relied heavily on the Model View ViewModel pattern. But while this pattern is definitely the best thing ever, it took me a while to come to grips with it:

First of all, I have a mostly Windows Forms and ASP.Net background. With these technologies, I typically applied different separated presentation patterns, such as Model View Presenter. So when I tried to build WPF and Silverlight applications, I tried to apply the same techniques. But what I found was, that building WPF and Silverlight applications is significantly different from those other technologies. When I tried to apply the Model View ViewModel pattern, I kept running into questions. How do I do “X” in this pattern.

At first glance, the Model View ViewModel does not differ that much from other separated patterns such as Model View Presenter. It certainly tries to achieve similar goals, but it does it in subtly different ways.

In this series of blog posts, I’m going to describe how to apply the Model View ViewModel pattern and what kind of challenges you’ll have to overcome and what kind of decisions you’ll have to make. Over the next couple of weeks, I’m going to be writing about these topics:

How do I:

(Inside the MVVM pattern)

(When applying the MVVM pattern to an application)

  • Instantiate my Views / ViewModels
  • Create a logical ViewModel structure of my application
  • Implement automatic datatemplate selection in Silverlight

Hope you’ll find these topics interesting. If there are specific things you are struggling with, let me know. If i have time, I’ll try to write something about that as well.

<Download demo app>

Note, you’ll need to download the following references:

As I’m publishing new blog posts, I’ll keep updating this app, so check back sometimes for updated versions..


the difference between model-view-viewmodel and other separated presentation patterns

the difference between model-view-viewmodel and other separated presentation patterns: "

This is the second blog post in a series on the Model View ViewModel pattern. Before I’m going to dive into the details of the Model View ViewModel pattern, I thought it is handy to describe the differences and similarities between this pattern and other separated presentation patterns.

<Back to the intro>

<Next: Implement the Model View ViewModel pattern>

There are quite a number of Separated Presentation patterns out there. Model View Controller, Model View Presenter, Presentation Model, Passive View, Supervising Controller, Model- View-ViewModel and many many more:


When you look at these patterns, sure, the arrows are in different directions. But is that the only difference? Is a controller the same as a presenter or a presentation model? How would you compare Model View Presenter vs Model View ViewModel. In this blog post, I’m going to describe these differences and similarities between the most common separated presentation patterns.

Building an UI without Separated presentation patterns

How would you build a UI without using a separated presentation pattern. Typically, you’d create a form or user control, drag your controls on it and put the logic in the code behind. The code in the Code behind is very closely coupled to the UI, because it directly interacts with the controls on the screen. This approach is nice and straight forward, but only for really simple views. Because when the logic becomes more complicated, maintaining such a UI can become a nightmare!

The root of the problem lies in the fact that building a UI this way violates the single responsibility principle. This principle states: “A class should have only a single reason for change.” If a UI component has code for visualization, logic and data, it effectively has several reasons for changing. For example, if you wish to change the type of controls that are used to display the data, that change should not affect the logic. However, because the logic is so closely tied to the controls, it has to change too. This is a ‘code smell’ that signals that the single responsibility principle is violated.

So the Form or User Control holds both the code to draw the UI (controls, etc..), the logic of the UI (What happens when you click a button) and the data of the UI (The data that the UI works with), you’ll run into the following problems

  • Decreased Maintainability
    A change in either the UI, the logic or the data will most likely cause changes in the others. This makes it a lot harder to make changes and decreases maintainability of the UI.
  • Decreased Testability
    The logic and Data of an application can be written in such a way that each component can be unit tested in isolation. However, the UI related code is inherently very hard to Unit Test, because it often needs user interaction to trigger logic in the UI. Also, any visualization often needs to be judged by a human to see if it ‘looks right’. If the UI related code is mixed with Logic and Data, you loose the testability of the Logic and Data. Note, there are automated UI testing solutions available. However, they ‘mimic’ the user interaction. They are typically harder to setup and maintain than unit tests, but also they are often only useable as integration tests, because they need the entire application to be set up.
  • Decreased Reusability
    If your UI related code is mixed with logic and with data, it becomes a lot harder to make that code reusable.

The goals of separated presentation patterns

While the individual patterns are quite different, the goals of these patterns are actually quite similar. Separate UI related code (Views) from Logic related code (Presenters, Controllers, ViewModels, etc..) and from the Data (Models). This allows each of these to evolve independently. For example, you are able to change the Look and Feel of your application, without affecting the logic or the data.

Secondly because the Logic and Data is separated from the visualization, the logic and the data can be unit tested in isolation. For very straightforward applications, this might not be very significant. For example, if your application is a simple data editor. However, if you have more complicated UI logic, it will quickly become very valuable to be able to automatically verify that your UI logic works as expected.

Model View Controller pattern

One of the very first separated presentation patterns was the Model-View-Controller pattern. This pattern was developed by Trygve Reenskaug.

In 1979!!!! (I wasn’t even born then).

Anyway, this pattern was developed for building Smalltalk applications. But in those days, computer programming was a bit different than today. There was no Windows. No graphical user interface. No Controls library. If you wanted a UI, you had to draw it yourself. If you wanted to interact with input devices such as keyboards. (Where there even mice in those days?)

But what Trygve did was quite revolutionary. Where everybody was mixing the visualization code, User interaction code, logic and data together, he came up with a pattern to separate these into separate classes, each with a distinct responsibility.

The problem with the MVC pattern is that it’s very likely the most misunderstood pattern in the world. And I think it’s caused by the naming. Trygne originally called the pattern Model-View-Editor, but later settled on the name Model View Controller. Now I can understand what a Model is (data) and what a View is (Something i can look at, the UI). But what is a controller? Is an ‘Application Controller’ the same controller as the controller in the MVC pattern? (No, but you can see where some of the confusion comes from)


So what are those Models, Views and Controllers

  • Model
    The model typically is the data of your application and the logic to retrieve and persist that data. Often, this is a domain model that can be based on a database or the results from web services. In some cases, that domain model maps perfectly to what you see on the screen, but in other cases it has to be adapted, aggregated or extended to be usable.
  • View
    The View was responsible for drawing the UI on the screen. Without windows or controls, that meant drawing, boxes, buttons, input fields, etc on the screen. The View can also monitor the model and display any data in it or update itself if the data changes.
  • Controller
    The controller is responsible for handling the User Input and then updating the Model or the View. So if the user is interacts with the application, IE: presses a button on the keyboard, moves the mouse, the controller is notified of that user gesture and decides what to do with it. Maybe it should update the view, maybe it should update the model.

I whipped up the following example to illustrate what a Controller would look like in a ‘pure’ MVC implementation. I happened to implement it in normal asp.net (not asp.net Mvc), but without relying on any of the controls. So it’s more traditional asp style. (Ok, I know this is not a pretty example, but I hope it gets the point across of what a controller was meant to do.)

   1: public class Controller

   2: {

   3:     private readonly IView _view;


   5:     public Controller(IView view)

   6:     {

   7:         _view = view;


   9:         HttpRequest request = HttpContext.Current.Request;

  10:         if (request.Form["ShowPerson"] == "1")

  11:         {

  12:             if (string.IsNullOrEmpty(request.Form["Id"]))

  13:             {

  14:                 ShowError("The ID was missing");

  15:                 return;

  16:             }


  18:             ShowPerson(Convert.ToInt32(request.Form["Id"]));

  19:         }

  20:     }


  22:     private void ShowError(string s)

  23:     {

  24:         _view.ShowError(s);

  25:     }


  27:     private void ShowPerson(int Id)

  28:     {

  29:         var model = new Repository().GetModel(Id);


  31:         _view.ShowPerson(model);

  32:     }

  33: }

After many years, the programming paradigm changed somewhat. The concept of a control emerged. A Control encapsulates both the visualization (It draws itself), but also the user interaction. A button knows what to do if you click it. A textbox knows what to do if you type text in it. This reduces the need for a controller, so the Model View Controller pattern became less relevant. However, since there was still a need for separating out the logic of the application from the Controls and the data, an other pattern called Model View Presenter became more popular.

Most examples of the MVC pattern focus on very small components, such as building a text box or building a button. With a bit more modern UI technologies (Visual basic 3 is modern compared to 1979 smalltalk), you typically don’t need to apply this pattern. Unless you are developing your own control using very low level API’s. For example, if you want to build a completely custom control using Direct X, then you might be interested in this pattern.

The last couple of years MVC pattern became very relevant again, but for a different reason, with the advent of the ASP.Net MVC framework. The ASP.Net MVC framework does not use the concept of controls in the same way as the normal ASP.NET framework does. In the ASP.Net MVC framework, a View is an ASPX control that renders HTML. And the controller again handles the user gestures, because it receives the HTTP requests. Based on the http request, it determines what to do (update a model or display a particular view).

Model View Presenter pattern

So after the rise of visual programming environments and the introduction of controls that encapsulated both the Visualization and the User Interaction code, the need for creating a separate controller class became less. But people still found the need for a form separated presentation, only this time at a higher abstraction level. Because it turned out that if you create a form that is composed out of several controls and also contains the UI logic and the data, The Model View Presenter pattern describes a way to separate out the visual elements (Controls) from the Logic (What happens when you interact with the controls) and the Data (what data is displayed in the view).


  • Model

    The model typically is the data of your application and the logic to retrieve and persist that data. Often, this is a domain model that can be based on a database or the results from web services. In some cases, that domain model maps perfectly to what you see on the screen, but in other cases it has to be adapted, aggregated or extended to be usable.

  • View

    The View is typically a user control or form that combines several (smaller grained controls) into a (part of a) user interface. The user can interact with the controls in the View, but when some logic needs to be started, the view will delegate this to the presenter.

  • Presenter

    The presenter holds all the logic for the view and is responsible for synchronizing the model and the View. When the view notifies the presenter that the user has done something (for example, clicked a button), the presenter will then update the model and synchronize any changes between the Model and the View.

One important thing to mention is that the Presenter doesn’t communicate directly to the view. In stead, it communicates through an interface. This way, the presenter and the model can be tested in isolation.

There are two variations of this pattern, Passive View and Supervising Controller.

Passive View

In the passive view, the view knows nothing about the model, but instead exposes simple properties for all the information it wants to display on the screen. The presenter will read information from the Model and update the properties from the model.

This would be an example of a passive view:

   1: public PersonalDataView : UserControl, IPersonalDataView

   2: {

   3:     TextBox _firstNameTextBox;


   5:     public string FirstName

   6:     {

   7:         get

   8:         {

   9:             return _firstNameTextBox.Value;

  10:         }

  11:         set 

  12:         {

  13:             _firstNameTextBox.Value = value;

  14:         }

  15:     }

  16: }

As you can see, this requires quite a lot of coding, both for the View but also for the Presenter. However, it will make the interaction between the View and the Presenter more testable.

Supervising Controller

In supervising controller, the View DOES know about the Model and is responsible for databinding the model to the view. This makes the interaction between the Presenter and the View a lot less chatty, but at the expense of testability of the View-Presenter interaction. Personally i hate the fact that this pattern is called “Controller”. Because the controller is again not the same thing as the controller in the MVC pattern and also not the same as an “Application Controller”.

This would be an example of a view in the Supervising Controller.

   1: public class PersonalDataView : UserControl, IPersonalDataView

   2: {

   3:     protected TextBox _firstNameTextBox;


   5:     public void SetPersonalData(PersonalData data)

   6:     {

   7:         _firstNameTextBox.Value = data.FirstName;

   8:     }


  10:     public void UpdatePersonalData(PersonalData data)

  11:     {

  12:         data.FirstName = _firstNameTextBox.Value;

  13:     }

  14: }

As you can see, this interface is less granular and puts more responsibilities in the View.

Presentation Model

Martin Fowler describes a different approach on achieving separation of concerns on his site, that’s called Presentation Model. The Presentation Model is a logical representation of the User Interface, without relying on any visual elements.


The presentation model has several responsibilities:

  1. Hold the logic of the UI:

    Same as the Presenter, the Presentation Model holds the logic of the UI. When you click a button, that click is forwarded to the Presentation Model, which then decides what to do with it.

  2. Massage the data from the model to be displayed on the screen:

    The presentation model can convert the data in the model so it can more easily be displayed on the screen. Often, the information contained in the model cannot directly be used on the screen. You might need to alter the information (IE: convert data types), enrich the information (IE: summations) or aggregate information from several sources. This is especially likely if you don’t have full control over the model. For example, you get information from an 3rd party web service, or from a database of an existing application.

  3. Store the state of the UI:

    Often, the UI needs to store additional information that has nothing to do with the domain model. For example, which item is currently selected on the screen? What validation errors have occurred? The presentation model can store this information in properties.

The View can then easily read the information from the Presentation Model and get all the information it needs to display the view. One advantage of this approach is that you can create a logical and fully unit testable representation of your UI, without relying on testing visual elements.

The Presentation Model pattern doesn’t really describe how the view then uses the data in the Presentation Model.

Model View ViewModel

And then there is Model View ViewModel, also known as MVVM or just the ViewModel pattern. It looks surprisingly similar to the Presentation Model pattern:


In fact, the pretty much the only difference is the explicit use of the databinding capabilities of WPF and Silverlight. Not surprising, because John Gossman was one of the first persons to mention this pattern on his blog.

The ViewModel doesn’t communicate directly with the View. Instead it exposes easily bindable properties and methods (in the form of Commands). The View can databinding those properties and commands to query information from the ViewModel and call methods on the ViewModel. It’s also not required that the View knows about the ViewModel. XAML Databinding uses a form of reflection to bind properties of the ViewModel, so theoretically you can use any ViewModel with the View that exposes the right properties.

Some of the things I really like about this pattern when applied to Silverlight or WPF are:

  • You get a fully testable logical model of your application. I’ll talk more about this in further posts.

  • Because the View Model offers everything the view needs in easily consumed format, the view itself can be fairly simple. In fact, a designer can play with the look and feel in Expression Blend and change it without affecting the UI.

  • Lastly, you can avoid using code behind. In a later blog post, I’ll describe how to do this in more detail. Now this is a point of debate amongst View Model fans. I personally feel that you often don’t need code behind and that there are often better ways of solving it. Ok, sometimes you’ll need to do some tricks (like create attached behaviors) but they offer really nice and reusable solution. However, I also recognize that not everybody likes XAML markup and the XAML way of expressing databinding. The ViewModel pattern doesn’t force you to use or avoid code behind. Do what feels right to you.


I hope this description of the most common Separated Presentation patterns helps you in understanding their differences.


Implementing the Model View ViewModel pattern

Implementing the Model View ViewModel pattern: "

In this third part of my series of blog posts on the ViewModel pattern, I’m going to demonstrate how to implement a simple example of the ViewModel pattern. Not to worry, we’ll dive into more exiting examples later.

<Back to intro>

<Back to: The difference between MVVM and other Separated presentation patterns>

<Next: Adapting a simple vs complex model>

The ViewModel

So what is a ViewModel? And how does it differ from a View or the Model. Consider the following example. Suppose you would build Paint using WPF or Silverlight, using the MVVM pattern:


The View obviously determines what is displayed on the Screen. And the Model, well that will likely be the Image. But the application works with more data than ‘just’ the Document. This extra data is mostly the State of the UI. What brush is currently selected? What is the ‘zoom’ percentage? While it is possible to store this information in the View itself, this is usually a bad practice. For example, the zoom slider bar could be the place where you would store the zoom percentage. However, when more elements on the screen need to use the Zoom percentage, this value quickly becomes very hard to manage.

Model for the View

The ViewModel is a model for the view. Therefore, it hold’s all the state of the view as well as the logic that operates on the state. The ViewModel exposes this data and logic in such a way that the View can very easily access it. However, the ViewModel should not expose or interact directly with UI elements.

Another responsibility of the ViewModel is to adapt the Model to the View. Typically the Model is a domain model (we’ll dive into that more in a later blog post). If you have full control over the model, then typically you can build it so that the model itself is very easily databindable. However, if you don’t have control over the model, for example, you are getting it from an external system, then the ViewModel might need to adapt the model to the view. For example, by adding aggregations, combining information from different models or simply by implementing INotifyPropertyChanged to enable the ViewModel notifying the View that properties have changed.

The MVVM pattern

So the following picture shows the MVVM pattern as how you would typically implement it in WPF or Silverlight:


The View is typically implemented as a UserControl or DataTemplate (in WPF). It uses Databinding to read and update information on the ViewModel. For example, the ViewModel can expose a public property Name that can be bound to a textbox.

If the view needs to communicate to the ViewModel, there are several options:


To route the Click event from a button to a ViewModel, the easiest way is to implement a Command. The Command pattern describes an object that can invoke functionality at a later point in time. In this case, when the user clicks a button. We’ll dive into commands later in this post.

This defines the Commands in XAML:

   1: // Define the Commands

   2: public ICommand ShowCalorieKingInfoCommand { get; private set; }

   3: public ICommand ShowIngredientInfoCommand { get; private set; }


   5: // Initialize the commands in the constructor with a delegate command.

   6: public MealDetailsViewModel(IDialogService dialogService)

   7: {

   8:     this.ShowCalorieKingInfoCommand = new DelegateCommand<object>(ShowMealCalorieKing);

   9:     this.ShowIngredientInfoCommand = new DelegateCommand<Ingredient>(ShowIngredientInfo, CanShowIngredientInfo);

  10: } 


  12: // The methods called when the commands are invoked

  13: private void ShowMealCalorieKing(object notUsed) {..}

  14: private bool CanShowIngredientInfo(Ingredient selectedIngredient) {..}

  15: private void ShowIngredientInfo(Ingredient selectedIngredient) {..}

This snippet shows an example how to bind a command to a button in XAML

<Button Margin="10, 10, 10, 10" Content="Show information on CalorieKing.Com"
Commands:Click.Command="{Binding ShowCalorieKingInfoCommand}"/>

Pretty much only buttons allow you to use Commands out of the box. Now it’s possible (and not too hard) to create your own commands using attached behaviors).

2 way bindable properties

You can also use TwoWay databinding to notify the ViewModel that something has changed. For example, the following codesnippet shows how the DataGrid Control has a SelectedItem property. If you TwoWay databind this property to a property on the ViewModel.

Here’s the property in C#:

   1: public Ingredient SelectedIngredient

   2: {

   3:     get { return _selectedIngredient; }

   4:     set

   5:     {

   6:         if (_selectedIngredient == value)

   7:             return;


   9:         _selectedIngredient = value;

  10:         OnPropertyChanged("SelectedIngredient");

  11:     }

  12: }

You can see that it also supports the INotifyPropertyChanged event. This means that the View will be notified if this value is changed in the ViewModel. And this is what the XAML would look like:

<data:DataGrid ItemsSource="{Binding Meal.Ingredients}"
SelectedItem="{Binding SelectedIngredient, Mode=TwoWay}" >

When I first started using the ViewModel pattern, I overlooked this capability. For example, I was looking for a way to attach functionality to the SelectedItemChanged event of the DataGrid. But two way databinding works a lot more directly. Just don’t forget to add the “Mode=TwoWay” tag ;)

Bind ViewModel methods to events from controls

The Caliburn framework allows you to bind public methods on the ViewModel directly to your controls in XAML. While this is a really cool technology, I also believe it makes your XAML more complex, because effectively, you are now programming (calling methods) in XAML. So I would personally try to either use commands, use two way databinding or implement an attached behavior (more on this subject later).

Code behind

It is always possible to use Code Behind to communicate between the View and the ViewModel. Whether this is a good idea is a topic of hot debate. I personally am of the opinion that there are better ways to solve this problem than to use code behind. In a later blog post, I’ll go into details why i think this is a bad idea and how you can avoid this. But there are people who think differently.

ICommand interface

A common way to expose functionality from your ViewModel that your Views can interact with is by exposing Command objects. A command object implements the ICommand interface.

The ICommand interface has two methods:

  • Execute, which will fire the logic encapsulated by the command

  • CanExecute, which determines if the command can actually execute.

The CanExecute is interesting. It’s a common scenario that you might wish to disable certain functionality, based on the state of your UI. This can easily be accomplished with a command. Because, when you bind a button to a command and CanExecute returns false, then the button will automatically become disabled.

Commands also have another advantage: They decouple the invocation from the actual logic. This allows for interesting scenario’s:

  • Binding multiple ui elements to a command

    Consider for example a SaveCommand. Often you don’t just have a Save Button, but also a Save menu item, and perhaps a save keyboard shortcut that will fire the same functionality. All these user gestures can be bound to the same command.

  • Chaining commands together

    You might also wish to bind several commands to a single UI element. For example, a certain type of ViewModel can expose a Save Command. However, you can have several instances of that ViewModel (with the corresponding view) open at any given time. A Save All button can be bound to all SaveCommands on all those ViewModels.

Silverlight doesn’t have Commanding support built in. Fortunately, it does support the ICommand interface, so there are several libraries available that provide Silverlight implementations of the ICommand interface. For example Prism (aka the Composite Application Guidance for WPF and Silverlight) and the MVVM Toolkit both provide a DelegateCommand implementation.

In my demo application, I’m also demonstrating the use of the DelegateCommand.

The INotifyPropertyChanged interface

One thing that you’ll find yourself implementing on your ViewModels the time is the INotifyPropertyChanged interface. This interface allows your ViewModel to notify the View of changes to properties.

This code snippet shows how to implement this pattern:

   1: // Public event (for the interface)

   2: public event PropertyChangedEventHandler PropertyChanged;


   4: // Protected method for invoking the event from code

   5: protected virtual void OnPropertyChanged(string property)

   6: {

   7:     var handler = PropertyChanged;

   8:     if (handler != null)

   9:     {

  10:         handler(this, new PropertyChangedEventArgs(property));

  11:     }

  12: }


  14: // Example property that triggers the property. 

  15: public Ingredient SelectedIngredient

  16:  {

  17:      get { return _selectedIngredient; }

  18:      set

  19:      {

  20:          // IMPORTANT: only trigger the event if someting actually changes!

  21:          if (_selectedIngredient == value)

  22:              return;


  24:          _selectedIngredient = value;

  25:          OnPropertyChanged("SelectedIngredient");

  26:      }

  27:  }

One important thing: before invoking the event in the property, check if the value has actually changed. This helps preventing never ending loops when properties are chained together.

If you don’t like the repeating code you’ll get when implementing properties with INotifyPropertyChagned, you can also use ObservableObjects as properties, as I’m describing (among other things) in this blog post:


What not to do in a ViewModel

There are a couple of things you shouldn’t do in your ViewModels:

  • Expose or interact with visual elements in your ViewModel

    Don’t try to expose Visual Elements, such as Buttons or other views from your ViewModel. This ties your UI to Visual Elements and makes it hard to test in isolation. Now you might run into the situation where your ViewModel needs to determine which view to display. In a later blogpost, i’ll describe how your ViewModel can be responsible for the logical ViewModel selection and use a DataTemplate to create the Visualization.

  • Try to control the View too directly from your ViewModel

    You should try to keep your ViewModel logical, rather than Visual. For example, if you want to color a control red in error situations, you could expose an “IsControlRed” property, or expose a brush in the red color. It’s usually better to expose the logical property, such as “HasError”. Then the UI designer can decide if the color of the control should be red or purple in an error situation.


This blog post describes the basics about implementing the MVVM pattern. In later blog posts, we’ll dive into more interesting scenario’s.