Month: June 2009

WPF and MVVM tutorial 06, start up form.

Today we are going to create the start-up form of our project and use the first ViewModel to run the application logic.

The result we want to obtain will be:


The View Model for the Startup form.

In our project, let’s go to the ViewModel section and create a new class. This class will inherit from the basic View Model class like the code below:

  1: public class StartViewModel : ViewModel {
  3:    public StartViewModel() {
  5:    }
  6: }

Then we need to create 2 commands that we will then associate to two buttons in our XAML form. One will start the application and one will shut-down the application.

This is the implementation we need to do in our ViewModel in order to create the Relay Command:

  1: public ViewCommand startCommand;
  2: public ViewCommand StartCommand {
  3:     get {
  4:         if (startCommand == null)
  5:             startCommand = new ViewCommand
  6:                  (param => this.StartApplication());
  7:         return startCommand;
  8:     }
  9: }

Then we need a delegate for the relay command in this way:

  1: private void StartApplication() {
  2:   NavigationActions.OpenCustomersView();
  3: }

The first XAML Form of our Application.

I am not a guru in windows design, especially the fancy UI but the final project will have a startup form like this one:


First of all add a new XAML form into the UI layer and then let’s see at the XAML code:

  1: <Window x:Class="MVVM.WPFView.Start"
  2:     xmlns=""
  3:     xmlns:x=""
  4:     xmlns:vm="clr-namespace:MVVM.ViewModel;assembly=MVVM.ViewModel"
  5:         Title="MVVM AdventureWorks Application." 
  6:         Height="500" Width="500"
  7:         WindowStartupLocation="CenterScreen" WindowState="Normal"
  8:         WindowStyle="None">

If you look at the line 4, we added a reference to our viewmodel namespace. In this way we can use in a declarative way the objects in the viewmodel namespace, directly into XAML (I personally hate to use procedural code into XAML!)

  1:     <Window.DataContext>
  2:         <vm:StartViewModel />
  3:     </Window.DataContext>

Then we add as a resource, the StartViewModel view model into our Window. In this way when the window will load the XAML declaration will inform the CLR to load a default instance of our view model.

Now let’s view the two buttons:

  1: <Button Name="btnStart" Margin="5" 
  2: IsDefault="True" 
  3: Command="{Binding Path=StartCommand}">

The binding will be the Relay Command we have previously created in the View model class. Easy right?

Now, the next step will be to build the View model to show all the customers. Then we will build some specific command for the C.R.U.D. operations.

Stay tuned!


WPF and MVVM tutorial 05, The basic ViewModel.

As we saw in the previous posts, a view model should be an abstract implementation of what the view needs to show about the model. We should implement an observable collection of something, we should implement an INotifyPropertyChanged interface and we should have a collection of RelayCommands.

For these reasons, it simply to understand that we need a basic abstract ViewModel class, just to recycle some code.


The Basic View Model.

  1: namespace MVVM.ViewModel {
  2:     public abstract class ViewModel:INotifyPropertyChanged,IDisposable {
  4:         INavigationActions navigator;
  6:         public ViewModel() {
  7:             navigator = Application.Current as INavigationActions;
  8:             if (navigator != null) {
  9:                 navigator.PropertyChanged += application_PropertyChanged;
 10:             }
 11:         }
 13:         void application_PropertyChanged(object sender, PropertyChangedEventArgs e) {
 14:             if (string.IsNullOrEmpty(e.PropertyName) || e.PropertyName == "View")
 15:                 OnPropertyChanged("View");
 16:         }
 18:         public INavigationActions NavigationActions {
 19:             get {
 20:                 return navigator;
 21:             }
 22:             set {
 23:                 if (navigator != value) {
 24:                     SetAction(value);
 25:                     OnPropertyChanged("NavigationActions");
 26:                 }
 27:             }
 28:         }
 30:         protected virtual void SetAction(INavigationActions value) {
 31:             if (navigator != null)
 32:                 navigator.PropertyChanged -= application_PropertyChanged;
 33:             navigator = value;
 34:             if (navigator != null)
 35:                 navigator.PropertyChanged += application_PropertyChanged;
 36:         }
 38:         #region INotifyPropertyChanged Members
 39:         /// <summary>
 40:         /// Raised when a property has a new value
 41:         /// </summary>
 42:         public event PropertyChangedEventHandler PropertyChanged;
 43:         /// <summary>
 44:         /// Raise the event
 45:         /// </summary>
 46:         /// <param name="propertyName">Property name that has new value</param>
 47:         protected virtual void OnPropertyChanged(string propertyName) {
 48:             PropertyChangedEventHandler handler = this.PropertyChanged;
 49:             if (handler != null) {
 50:                 var e = new PropertyChangedEventArgs(propertyName);
 51:                 handler(this, e);
 52:             }
 53:         }
 54:         #endregion
 56:         #region IDisposable Members
 57:         /// <summary>
 58:         /// Implementation of the dispose method
 59:         /// </summary>
 60:         public void Dispose() {
 61:             this.OnDispose();
 62:         }
 63:         /// <summary>
 64:         /// The child class should implement a personal dispose procedure
 65:         /// </summary>
 66:         protected virtual void OnDispose() {
 67:             //do nothing because abstract
 68:         }
 70:         #endregion
 71:     }
 72: }

A small summary of our code:

  1. An implementation of the INotifyPropertyChanged that we can use in the concrete views.
  2. An implementation of the IDisposable in order to clean our objects like collections and repositories.
  3. An INavigator interface to implement the navigation of our application. In this case I am using the navigator pattern for composite WPF applications. Beware because this is my implementation for the navigation but it depends on how you design your app (multi-win, tab, MDI).

The INavigator implementation.

The are thousands of ways to implement a navigator engine. The only common purpose in MVVM is that the View Model doesn’t know the View but the View knows the View Model. So in our example which part of the View can interact with the application and doesn’t need to know the View Model? The app.xaml file!

My idea is this one:


We will have a simple interface in the ViewModel namespace which will identify the navigation commands we want to execute:

  1: public interface INavigationActions:INotifyPropertyChanged 
  2: {
  3:     void OpenCustomersView();
  4:     void OpenCustomerView();
  5:     void OpenOrdersView();
  6:     void OpenOrderView();
  7:     void CloseCurrentView();
  8:     void CloseApplication();
  9:     bool QueryConfirmation(string title, string message);
 10:     void ShowError(string title, string message);
 11: }

In this way we can call everything from our viewmodel that doesn’t know the view.

Now we just need to implement the view in the Application file in this way:

  1: public partial class App : Application,INavigationActions,INotifyPropertyChanged {
  2:     #region INavigationActions Members
  4:     public void OpenCustomersView() {
  5:         CustomersView customersView = new CustomersView();
  6:         customersView.Show();
  7:     }
  9:     public void OpenCustomerView() {
 11:     }
 13:     public void OpenOrdersView() {
 15:     }
 17:     public void OpenOrderView() {
 19:     }
 21:     public void CloseCurrentView() {
 23:     }
 25:     public void CloseApplication() {
 26:         Application.Current.Shutdown();
 27:     }
 29:     public bool QueryConfirmation(string title, string message) {
 30:         return MessageBox.Show(title, message, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
 31:     }
 33:     public void ShowError(string title, string message) {
 34:         MessageBox.Show(title, message, MessageBoxButton.YesNo, MessageBoxImage.Error);
 35:     }

And there we go!!

Ops I forgot to mention that in the basic View Model we need to handle the INavigation

  1: public ViewModel() {
  2:     navigator = Application.Current as INavigationActions;
  3:     if (navigator != null) {
  4:         navigator.PropertyChanged 
  5:         += application_PropertyChanged;
  6:     }
  7: }

For the rest you need to wait the next tutorial!!


WPF and MVVM tutorial 04, The Commands.

In the previous posts we saw the basic of our project, the model (domain entities) and a simple repository.

Note: please note that the sample I wrote about an agnostic UnitOfWork is just to show you a simple pattern to handle L2S but it can be done better.

The ViewModel.

What is the view model? Well the simplest explanation is enclosed in this definition: the view model should be the datacontext of our view. It should provide the commands, the observable collections used in the view and the error logic.

Before starting to view how to build the basic abstract class for the viewmodel I want to talk about the Relay Command and the Routed Command and their differences.

Routed or Relay command?

I have found a useful explanation here, in the Josh Smith blog. Routed events are events designed to work in a tree of elements. When a user click the text over a button, the even travels over the tree until it will find the Click event of the chrome button.  This is how a button implements a routed events:

  1: public class Button:ButtonBase
  2: {
  3:    static Button()
  4:    {
  5:       Button.ClickEvent = EventManager.RegistedRoutedEvent
  6:          ("Click", RoutingStrategy.Bubble,
  7:           typeof(RoutedEventHandler), typeof(Button));
  8:    }
  9:    public RoutedEventHandler Click
 10:    {
 11:       add { AddHandler(Button.ClickEvent,value); }
 12:       remove { RemoveHandler(Button.ClickEvent,value); }
 13:    }
 14:    protected override void 
 15:       OnMouseLeftButtonDown(MouseButtonEventArgs e){
 16:       RaiseEvent(new RoutedEventArgs(Button.ClickEvent,this);
 17:    }
 18: }

The commands in WPF represent a more independent action from their user interface. Also WPF and NET expose a default set of commands that we can easily handle in our application, like:

Application command, ComponentCommand, MediaCommand, NavigationCommand and EditingCommand.

They inherit all, from the ICommand interface. So for each command you want to implement, it should inherit from ICommand in this way:

  1: #region ICommand Members
  3: public bool CanExecute(object parameter) {
  4:     return _canExecute == null ? true : _canExecute(parameter);
  5: }
  7: public event EventHandler CanExecuteChanged {
  8:     add { CommandManager.RequerySuggested += value; }
  9:     remove { CommandManager.RequerySuggested -= value; }
 10: }
 12: public void Execute(object parameter) {
 13:     _execute(parameter);
 14: }
 16: #endregion

So it becomes simple to understand that we should have a View Model abstract class that contains an abstract implementation of a collection of ICommand. Then we can inherits each view model from this one!

So our conclusion is that:

The key difference is that RoutedCommand is an ICommand implementation that uses a RoutedEvent to route through the tree until a CommandBinding for the command is found, while RelayCommand does no routing and instead directly executes some delegate. In a M-V-VM scenario a RelayCommand (DelegateCommand in Prism) is probably the better choice all around.

The final implementation of the Relay command should be something like:


In the next tutorial we will see how to build the abstract layer for a basic view model with a basic collection of relay commands.


WPF and MVVM tutorial 03, The user repository.

Before starting to view in depth our model, or to design the views, I want to complete the DAL layer. Now that we have our unit of work implementation and our data context we need to implement a couple of repositories.

If you want to view how it should work a repository, I suggest this interesting article from Martin Fowler. The presenter should be:

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection.

The Flow of our application.

During the time I saw different repositories. One for each entity, one for each View and so on. My approach, usually, is to use a relationship of 1-to-1 from the view and the repository. So in our case we will have:

image 1 – The user opens the program and has to decide (search a customer, view all customers)

2 – A list will be presented to the user (filtered or not) and he will have to select one customer.

3 – A third view will show the details of the user, with two sub-view (address and order details).

So this is the flow that we will follow. For these reasons, you will easily understand that we need a couple of repositories: A) a user repository, B) an order repository.


The User repository.

The user repository has to give us a way to execute any kind of CRUD operation against our database. So we should have something like:


Here there are some basic operations we must be able to accomplish with our repository.

1) Get a specific Customer or Get all of them.

2) Add, Update or Drop a Customer.

3)Commit the changes to the data-model.



The code is very simple. First of all we need to create a sealed repository, so that nobody will play with it, for this purpose there is the IUnitOfWOrk interface …

  1: public sealed class CustomerRepository {
  2:     //Create an istance (it's static) of our Unit of Work
  3:     private IUnitOfWork _service;
  4:     //but let's give it a read-only access
  5:     public IUnitOfWork Service {
  6:         get { return _service; }
  7:     }
  8:     //create a new istance of the Unit of work
  9:     public CustomerRepository() {
 10:         _service = new UnitOfWork();
 11:     }

Then we need to implement the custom methods to retrieve the information we need from our model. Fortunately we have a generic unit of work so the code behind it’s very very simple!

  1: //Add a new customer
  2: public void AddCustomer(Customer _customer) {
  3:     Service.Add<Customer>(_customer);
  4: }
  5: //Drop an existing one
  6: public void DeleteCustomer(Customer _customer) {
  7:     Service.Delete<Customer>(_customer);
  8: }
  9: //Update an existing dirty customer
 10: public void UpdateCustomer(Customer _customer) {
 11:     Service.Update<Customer>(_customer);
 12: }
 13: Get a specific customer
 14: public Customer GetCustomer(int id) {
 15:     return Service.GetById<Customer>(p => p.CustomerID == id);
 16: }
 17: //Get all of them
 18: public IList<Customer> GetAllCustomers() {
 19:     return Service.GetAll<Customer>();
 20: }

We should also implement a filtered GetAllCustomers but we will use the View Model to do that in our example.

Customer class diagram.

Now we are pretty fine with our Customer model. What we have know is a model, a repository and a CRUD implementation for the customer and the related entities (Address and so on …). The final result in our DAL layer is this one:


Great we can already build now 3 views (CustomersView, CustomerView, FilteredCustomersView) just by using one repository. TO be honest we should be able to do everything but I want to keep separate the Order section.

In the next step I will give an overview of the ViewModel, and the View interaction, then we will start to build the views and then the relative ViewModels.

Ndr. I saw that this series of articles is being read by a nice number of people. Please post any ideas, suggestion or whatever you think about … I will appreciate.


WPF and MVVM tutorial 02, The model.

In the first part of this tutorial we saw the MVVM model and how it works.

In this part of our tutorial we will work directly with the Entity Model and LinqToSQL. I am using a database-first approach so in my opinion using LinqToSQL will be better then Entitiy Framework. I am going also to show you an easy way to build a custom Unit Of Work to manage the context status with Linq 2 SQL.

The Visual Studio Project.

First of all open a blank Visual Studio solution, I called it WPF.Tutorial.VMMV. Add two projects on it: 1) WPF Application …UI and 2) Class Library (…DAL).

The final layout should be this one (in my picture the model is already inside).

New Picture (8)

The Data model.

If you have installed the Adventure Works database in the past you already know what I am talking about. The model I will use in the tutorial will come up with this layout:

New Picture (7)We will have a customer with the personal information and the related orders with the order information.

Go into the DAL project and from the menu choose add new file –> LinqToSQL and call it DataModel. Now you need to connect you data model into your AW database and drag in the design pane the tables you need. At the end you should come up with the same layout I have in the previous picture.

The Unit of Work.

If you do not what I am talking about, this is the explanation by Martin Fowler.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.

Of course with LinqToSQL we do not need a Unit of Work because L2S by itself is the data context, but because it is not able to manage the disposing in a good way, here are my 2 cents about.

We need a contract, in this way an interface in the DAL that will implement the Unit of Work:


First of all let’s build the C.R.U.D. implementation into a simple interface. In this case I am going to use the generics and the Linq expression because my project will work only with Linq so I do not need an high level of abstraction:

  1: using System;
  2: using System.Collections.Generic;
  4: namespace WPF.Tutorials.VMMV.DAL {
  5:     public interface IUnitOfWork {
  6:         //Basic C.R.U.D. operations
  7:         void Add<T>(T _entity) where T : class;
  8:         void Delete<T>(T _entity) where T : class;
  9:         void Update<T>(T _entity) where T : class;
 10:         void Commit();
 11:         //Basic Select operations
 12:         IList<T> GetAll<T>() where T : class;
 13:         T GetById<T>(Func<T, bool> _condition) where T : class;
 14:     }
 15: }

Now we need the real Unit of Work that will inherit from our contract. We want also to inherit from IDisposable because otherwise we will not be able to keep alive our datacontext during the crud operations.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  6: namespace WPF.Tutorials.VMMV.DAL {
  7:     //Inherits IUnitOfWork and IDisposable
  8:     public class UnitOfWork:IUnitOfWork,IDisposable {
  9:         //A Static instance of the Linq Data Context
 10:         private static DataModelDataContext _service;
 11:         //The default constructor
 12:         public UnitOfWork() {
 13:             _service = new DataModelDataContext();
 14:         }

Now, the second step is to translate the UoW in something readable for Linq:

  1: //Add a new entity to the model
  2: public void Add<T>(T _entity) where T: class {
  3:     var table = _service.GetTable<T>();
  4:     table.InsertOnSubmit(_entity);
  5: }
  6: //Delete an existing entity from the model
  7: public void Delete<T>(T _entity) where T: class {
  8:     var table = _service.GetTable<T>();
  9:     table.DeleteOnSubmit(_entity);
 10: }
 11: //Update an existing entity
 12: public void Update<T>(T _entity) where T : class {
 13:     var table = _service.GetTable<T>();
 14:     table.Attach(_entity,true);
 15: }
 16: //Commit all the pending changes in the data context
 17: public void Commit() {
 18:     _service.SubmitChanges();
 19: }
 20: //Get the entire Entity table
 21: public IList<T> GetAll<T>()where T : class {
 22:     return _service.GetTable<T>().ToList();
 23: }
 24: //Get the first occurence that reflect the Linq Query
 25: public T GetById<T>(Func<T, bool> _condition) where T : class {
 26:     return _service.GetTable<T>().Where(_condition).FirstOrDefault();
 27: }

Now we have a complete Unit of Work that we will use in each repository. Ops I forgot to mention that we will not have a real repository in our solution but a view model …


WPF and MVVM tutorial 01, Introduction.

With Microsoft WPF technology, a new pattern is born and is going to be called MVVM (Model View ViewModel). This pattern is an hybrid from the old MVC and the old MVP patterns. Why a new pattern for the presentation?

  1. First of all WPF technology is giving us a kind of technology that can completely change the approach to design and code the UI. With the VMMV we can completely design an agnostic UI that doesn’t know the Model we are going to pass to it.
  2. Recycle, I will show you in this tutorial how to simply convert a WPF application into a Silverlight app.
  3. Better delegation and better design for a real n-tier application. In this example we will use LinqToSQL and WPF to build a complete n-tier application with the VMMV.
  4. Something that I do not like, TESTING THE UI!! Yes we can test the UI with WPF and VMMV combination.
  5. Abstractation. Now the view can be really abstract and you can use just a generic.xaml file and then give a style template to your model.

This is the schema (in my opinion) on how it should work an application with WPF and the VMMV implementation:


  • MODEL: anyone that has already worked on an n-tier application knows what it is. The model is the group of entities that will be exposed.
  • VIEW: the view is the graphical code XAML used to generate the UI, nothing more then that.
  • VIEWMODEL: the model for the view … or … the view for the model?! Anyway is a model of the view.

Before starting this tutorial I suggest you to download:

The next tutorial will show you how to create a simple DAL layer with LinQtoSQL and how we can implement the Unit of Work pattern to build a simple but solid data layer for our application.

You can also download the Visual Studio template here.