[MVVM + Mediator + ACB = cool WPF App] – The MVVM

The Model View ViewModel is quite a hot subject right now in the WPF community. If you never read about MVVM I suggest that you read the following before you continue reading

- Introduction to Model/View/ViewModel pattern for building WPF apps by John Gossman (MVVM daddy)

- WPF & Silverlight Line of Business UI Design Pattern by Karl Shifflett

- WPF Apps With The Model-View-ViewModel Design Pattern by Josh Smith


MVVM in my sample app

Let me start by showing you a class diagram of the application structure


As you can see in the image above we have 3 layers. We have our Views, the ViewModels and the Models. (Please note that you can have n Tiers yet I am focusing just on 2 Tiers here, View and ViewModel….)

The View

The view is the “component” that renders the data on screen. This should be done all in XAML and not in C#. Why? Well UIs are much better built in a declarative fashion instead of an imperative one.

The View can be developed by a designer by using tools such as Blend and should not require any need from a developer. In the View the designer should express his artistic creativeness without any constrains from the developers.

Besides this when you put code in the View, this code is super hard to Unit test. From experiance I must say that 99% of the code written in the UI layer is never tested.

Ok so the designer sets the colors of the buttons etc… BUT!!!!

A - what about the data?  From where can the designer get the data without having C# knowledge?
B – what about actions/events? How can a designer specify that when the button is clicked something should happen?

Well my friends that is the power of the WPF Databinding and the MVVM!

The ViewModel

The ViewModel is just a simple class (That has no coupling with the View and 100% unit testable). The ViewModel exposes data that the View can use to render the UI. Besides this the ViewModel also has Commands that the View can use to invoke actions. I will demo 2 pages that I created in the Sample App that explain how the ViewModel does this job.

A – what about the data?


To show you how the view renders data exposed by the ViewModel we will take the example in the screen shot above.

The ViewModel involved here is called ProjectListViewModel and the View is called ProjectList.xaml

The ViewModel exposes the data via a property called Projects. The property is shown below

   1: ObservableCollection<WPFDisciples.Backend.ProjectDetails> projects

   2:     = new ObservableCollection<WPFDisciples.Backend.ProjectDetails>();

   3: public ObservableCollection<WPFDisciples.Backend.ProjectDetails> Projects

   4: {

   5:     get { return projects; }

   6: }

As you can see this is simply a normal CLR property (not a DependencyProperty ). In this case the real magic is not in the property as such but in the type of Collection. Since the property exposes an ObservableCollection<T>, the databinding engine will listen to collection changed notifications and update the rendered data according.

This is how we bind to the data in the View’s XAML

   1: <ListView ItemsSource="{Binding Projects}"

In this XAML we are doing List binding. We are specifying to the ListView that it should bind to the Projects property. The question is the Projects property of what object?

By default the source of a Binding is the DataContext of the element. In this case the DataContext will be the ViewModel. We specify that in the constructor of the View. There are many other nicer ways of doing this initialization of ViewModel in the View such as by using Onyx(this is a super cool WPF project!!!!! you must try it) or Dependency injection (such as in PRISM)

   1: public ProjectList()

   2:         {

   3:             InitializeComponent();


   5:             var viewModel = new ProjectListViewModel(Dispatcher);
   6:             DataContext = viewModel;

   7:         }

B – what about actions/events?

So let’s say you have a button and you want something to happen when the user clicks the button. Well the approach that we have been using in .Net is events. So a button would have a Click event and you would register an event handler for the event. Yet is this the right approach? Can a designer do this? Can you easily unit test such a method? Well I would say not really or better not easily…

A much better method has been introduced in WPF, the Commands. With commands you can delegate the work (such as a Click event) to the ViewModel. By doing so, the Designer can just specify what command to use for a button and viola he is done. Besides that the ViewModel can be unit tested much easier.

enter data

The example I picked from the sample app is the Save button to add a new Project. This can be found ProjectDetailsViewModel.cs

Here is the code that I used to expose the Command

/// <summary>
/// Gets a Command to save the current project
/// </summary>
public SimpleCommand SaveProject { get; private set; }

Where SimpleCommand is a class that implements the ICommand interface. For more info on this visit this post.

and here is the code for the Command.

SaveProject = new SimpleCommand
                ExecuteDelegate = Save,
                //Can execute only if there are no errors
                CanExecuteDelegate = x => String.IsNullOrEmpty(Project.Error)


This article should have given you a basic idea of how the M V VM works… Next post will discuss how to overcome some of the problems with MVVM. I will show you how you have to start thinking in databinding so that you implement MVVM in a proper way.