Read part 1 here, part 2 here or part 3 here.

This is a sort of summary post of my MVVM Pattern 101 series, talking about the frameworks available for MVVM development. There are many open-source frameworks available for MVVM-based development. Most of the frameworks support WPF as well as Silverlight including the new Windows Phone 7 platform. Of these frameworks, notable ones are Prism from Microsoft’s P&P team, Caliburn and MVVM Light. Prism is a composite UI framework for WPF and Silverlight. It also uses Inversion of Control (IoC)/Dependency Injection pattern. This allows you to use other IoC frameworks such as Spring.NET, Microsoft’s Unity or your own with MVVM development. Caliburn and MVVM Light are 3rd party MVVM-dedicated frameworks. If you would like to see a list of some of the MVVM frameworks available today, check here. The author has made the comparison itself as a Silverlight app!

    Talking about frameworks doesn’t mean you can’t develop your own. Watch a nice presentation on building own MVVM framework here.

This is 3rd of my multi-part series on MVVM 101. Read part 1 here and part 2 here.

From an implementation perspective, ViewModel is a just class satisfying certain requirements and you follow a few simple steps to have a working one. Remember the key part in MVVM is the VM, the real controller, because View is just your WPF UI and Model is either an entity object or data transfer object. Let us say we want to display some very basic details about an insurer; the listing dialog will display details such as first name, last name, state and his dependent list. Let us also assume we already have domain objects for the insurer and dependent entities (I deliberately made Dependents as a complex type to show how collection properties can be dealt with in MVVM). Here is our simple model:

public class InsuranceInfo
{
    public string FirstName {getset;}
    public string LastName {getset;}
    public List<FDependents> Dependents {getset;}
    public string State {getset;}
}

public class FDependents
{
    public string Relationship {getset;}
    public string DepName {getset;}
    public short Age {getset;}
}

 

A simple UI we are going to build our VM against to show the above model:

Let’s go ahead and get the missing piece – ViewModel. As a convention, all the VM classes have the “ViewModel” suffix and I am calling ours as InsuranceViewModel.

Step 1: Add special properties to the VM for the UI to bind to

    Any data displayed in the UI should have a corresponding property in the VM class. These properties are special in that any change to their values should be detectable by the binding engine and update the bound controls accordingly. Hence the VM should implement

INotifyPropertyChanged

interface and with collection properties wrapped by

ObservableCollection<>

.

public class InsuranceViewModel : INotifyPropertyChanged
{
    private string _fn;
    private string _ln;
    private string _state;

    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<FDependents> Dependents {getprivate set;}
    public string FirstName {
        get {return _fn;}
        set {
            if (_fn != value) {
                _fn = value;
                RaisePropertyChanged (“FirstName”);
            }
        }
    }
    public string LastName {
        get {return _ln;}
        set {
            if (_ln != value) {
                _ln = value;
                RaisePropertyChanged (“LastName”);
            }
        }
    }
    public string State {
        get {return _state;}
        set {
            if (_state != value) {
                _state = value;
                RaisePropertyChanged (“State”);
            }
        }
    }
    public EditCommand EditCmd {private set;get;}
    private void RaisePropertyChanged (string p) {
        if (PropertyChanged != null) {
            PropertyChanged (thisnew PropertyChangedEventArgs (p));
        }
    }
}

 

Note that I have implemented the properties as property methods instead of fields because we should raise property change notification whenever the property values are changed.

Step 2: Provide ICommand properties for applicable control events

Since our UI has save option, a command property,

EditCmd

of type

EditCommand

is also included in the above code. The command class looks like this:

public class EditCommand : ICommand {
    private InsuranceViewModel _vm = null;
    public event EventHandler CanExecuteChanged {
        add {CommandManager.RequerySuggested += value;}
        remove {CommandManager.RequerySuggested -= value;}
    }
    public bool CanExecute (object parameter) {
        if (parameter != null) {
            var cp = parameter as InsuranceViewModel;
            return !(cp.FirstName == “” || cp.LastName == “” || cp.State == “”);
        }
        else
            return true;
    }

    public void Execute (object parameter) {
        if (parameter != null) {
            var cp = parameter as InsuranceViewModel;
            MessageBox.Show (String.Format(“{0}, {1}, {2}”
                cp.FirstName, cp.LastName, cp.State));
        }
    }

    public EditCommand (InsuranceViewModel vm) {_vm = vm;}
}

It is very important that the command classes derive from

ICommand

. The

CanExecute

method tells if the action is available at any moment so that the control can disable itself or take appropriate action. This method will be called at appropriate times by the commanding infrastructure. The above code states that if at least one of first name, last name or state is empty, the Edit command should not be available.

Execute

method is called as a result of the control event (the event handler!). It is a common design that commands are initialized with a view model instance to delegate data service operations back to the view model itself.

Step 3: Hook up a ViewModel instance with UI markup

<Window x:Class=”MVVMDemo.MainWindow”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        Title=”MVVM Demo” Height=”352″ Width=”525″ Loaded=”Window_Loaded”>
    <Grid Height=”Auto”>
        <ListView Margin=”12,100,0,58″ Name=”lvwInsuranceInfo” 
                  SelectionMode=”Single” ItemsSource=”{Binding Path=Dependents}” 
                  HorizontalAlignment=”Left” Width=”352″>
            <ListView.View>
                <GridView AllowsColumnReorder=”False”>
                    <GridViewColumn Header=”Relationship” 
                                    DisplayMemberBinding=”{Binding Path=Relationship}” />
                    <GridViewColumn Header=”Name” 
                                    DisplayMemberBinding=”{Binding Path=DepName}” />
                    <GridViewColumn Header=”Age” 
                                    DisplayMemberBinding=”{Binding Path=Age}” />
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content=”_Close” Margin=”0,0,12,12″ Name=”btnClose” 
                Click=”btnClose_Click” HorizontalAlignment=”Right” Width=”105″ 
                Height=”24″ VerticalAlignment=”Bottom” />
        <Label Content=”First Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”10,10,0,0″ Name=”lblFN” Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <Label Content=”Last Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”10,40,0,0″ Name=”label2″ Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <Label Content=”State:” Height=”24″ HorizontalAlignment=”Left” Margin=”10,70,0,0″ 
               Name=”label3″ Padding=”0″ VerticalAlignment=”Top” 
   
            VerticalContentAlignment=”Center” />
        <Button Command=”{Binding Path=EditCmd}” CommandParameter=”{Binding}” 
                Content=”Save” Height=”24″ HorizontalAlignment=”Left” Margin=”123,0,0,12″ 
                Name=”btnSave” VerticalAlignment=”Bottom” Width=”105″>
        </Button>
        <TextBox Height=”24″ Margin=”93,10,139,0″ Name=”txtFn” VerticalAlignment=”Top” 
                 Text=”{Binding Path=FirstName}” />
        <TextBox Height=”24″ Margin=”93,40,139,0″ Name=”txtLn” VerticalAlignment=”Top” 
                 Text=”{Binding Path=LastName}” />
        <TextBox Height=”24″ Margin=”93,71,139,0″ Name=”txtCity” VerticalAlignment=”Top” 
                 Text=”{Binding Path=State}” />
        <Label Content=”Relationship:” Height=”24″ HorizontalAlignment=”Left” Margin=”370,100,0,0″ 
               Name=”label1″ Padding=”0″ VerticalAlignment=”Top” VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,124,12,0″ Name=”txtRelationshipName” 
              
   Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.Relationship}” 
                 VerticalAlignment=”Top” />
        <Label Content=”Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”370,149,0,0″ Name=”label4″ Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,171,12,0″ Name=”txtName” 
                 Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.DepName}” 
                 VerticalAlignment=”Top” />
        <Label Content=”Age:” Height=”24″ HorizontalAlignment=”Left” Margin=”370,201,0,0″ 
               Name=”label5″ Padding=”0″ VerticalAlignment=”Top” VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,231,12,0″ Name=”txtAge” 
                 Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.Age}” 
                 VerticalAlignment=”Top” />
    </Grid>
</Window>

As shown above, the UI controls are bound to the corresponding properties of the ViewModel instance. Note also how the Save button’s command property is wired to handle its click event. Finally, the code to set the main window’s data context looks like this: public partial class MainWindow : Window
{
    public MainWindow ()
    {
        InitializeComponent ();
    }

    private void btnClose_Click (object sender, RoutedEventArgs e) {
        this.Close ();
    }

    private void Window_Loaded (object sender, RoutedEventArgs e) {
        this.DataContext = new InsuranceViewModel ();
    }
}

In fact, this is also the entire code-behind for our demo application! All it does is just set a ViewModel instance to the window’s data context. In fact, this can also be moved to XAML markup to do it declaratively and get rid of

Window_Loaded

handler altogether.

Just for the demo purpose, the ViewModel class fills itself with some sample data when instantiated as shown below.

public InsuranceViewModel () {
    FirstName = “Dave”;
    LastName = “Watson”;
    State = “NJ”;
    Dependents = new ObservableCollection<FDependents> ();
    Dependents.Add (new FDependents () {
        Relationship = “Spouse”,
        DepName = “Milla Watson”,
        Age = 33 });
    Dependents.Add (new FDependents () {
        Relationship = “Son”,
        DepName = “John Watson”,
        Age = 10 });
    Dependents.Add (new FDependents () {
        Relationship = “Mother”,
        DepName = “Marie Gold”,
        Age = 65 });

    EditCmd = new EditCommand (this);
}

 

If everything works fine whether you set the data context via code or markup, the output screen will be:

Making any of the top three text boxes empty, automatically disables the Save button:

The text boxes on the right are hooked to the selected item in the list view to let the user edit the selected dependent. WPF binding engine provides certain validation logic out of the box. In our demo, the Age property is numeric and in the screenshot below, you get a red outline around the text box when it is empty or have non-numeric values without requiring any extra code or configuration. By the way, this is nothing to do with MVVM, but thought would highlight some of the tiny benefits WPF gives free.

That’s it! Here is the recap of what we have discussed so far:

  1. MVVM is all about separation of business logic & UI separation in WPF and promoting loose coupling
  2. The code-behind contains no business logic (other than hooking the ViewModel if you choose to) with proper MVVM in place
  3. WPF’s Binding and Commands are the backbones for MVVM. Without them, it is very difficult to implement the pattern in a useful way.
  4. You follow simple steps to create a working ViewModel class:
    1. Let the ViewModel class expose properties based on what the UI shows
    2. Implement
      INotifyPropertyChanged
    3. Create custom commands for applicable user actions/control events by implementing
      ICommand
    4. Bind its properties/commands to control properties in the XAML markup
    5. ViewModel classes are easily testable now
    6. Changing UI in future is as simple as designing a new one and consuming the existing VM. In fact, the UX team can try many prototypes and get feedback from the business with real data
    7. Since WPF and Silverlight front-ends can share almost the same ViewModel the effort required to support one front-end in addition to the above is lesser than having to building from the scratch. The bottom-line is reusability.

In some cases your code-behind may end up with extra code around MVVM hook up and other plumbing but that’s ok as long as you do not write any code that otherwise can be moved to ViewModel.

Alright, another claim is that MVVM enables independent (without UI intervention) testing of VM and downstream business logic easily. Restating one of the attributes of VM, it is purely UI independent and hence you can test the VM like any other class. For example, below is a simple NUnit test fixture for the

InsuranceViewModel

class. Like the UI, the test fixture in all respect is yet another consumer of VM.

[TestFixture]
public class InsuranceInfoVMUnitTest
{
    [Test]
    public void TestVMInit ()
    {
        var vm = new InsuranceViewModel ();
        vm.PropertyChanged += 
            (s, e) => {Debug.WriteLine (String.Format(@”Property {0} value changed.”, e.PropertyName));};
        Assert.IsNotNull (vm.Dependents, @”Dependents collection not initialized.”);
        Assert.IsNotNull (vm.FirstName, @”First name failed to initialize.”);
        Assert.IsNotNull (vm.LastName, @”Last name failed to initialize.”);
        vm.State = “PA”// Should write out a debug message; check Debug window
        vm.FirstName = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty FirstName.”);
        vm.FirstName = “Bill”;
        vm.LastName = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty LastName.”);
        vm.LastName = “Rogers”;
        vm.State = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty State.”);
        vm.EditCmd.Execute(vm);
        vm.State = “CA”;
        Assert.IsTrue (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check valid InsuranceInfo properties.”);
        vm.EditCmd.Execute(vm); // Save button click
        // Load current insurance info afresh & check for updated values
    }
}

 

Now that we have discussed MVVM at a reasonable level, lets us see the flip aspects of MVVM in WPF:

  1. MVVM requires extra code to be written; you have to implement a few interfaces and extend few base classes and all these would most probably take more time but the end advantages are many. It is better to invest upfront to save in future.
  2. For more sophisticated applications, you may have to write value converters to handle custom types in XAML markup.
  3. Some argue that ViewModel is the new code-behind and not a value adder when it comes to separation of concerns. This is motivated by the View (UI) delegating event handling to ViewModel class through command binding (
    ICommand.Execute

    method). This in a sense gives a feeler of having event handler methods in the ViewModel. Nevertheless, I am not against or favor of this point as it depends on the individual’s viewpoint.

  4. Out of the box, commands are available only to
    ButtonBase

    -derived controls,

     MenuItem

    , and

    HyperLink

    . For other controls, esp. selection controls such as combo box, list view, you have to resort to other ways (may be, I will cover this in a future post).

This is the continuation of my previous discussion on MVVM here.

With the advent of new designer tools such as Expression Blend, MVVM pattern suites WPF/Silverlight development very well. Expression Blend (or anything that produces WPF XAML) enables UX design and developer teams work independently, unlike early days of waiting for the UI to complete before the developers put their meat. Since both the teams work in parallel, there is a significant saving in the whole development effort. The most important advantage on the table is that the development team can now unit test their code with mock UIs before plugging the actual UI. Note that this mock UI is simply a test class that talks to ViewModel like a real WPF UI would do via property access and method invocation. Once the actual UI is ready, it’s just a matter of changing certain properties in the XAML (to hook to the ViewModel) and re-compiling it.

Let us look at the two WPF features that power MVVM:

Commands: In short, the Command pattern wraps an action to be executed on a target (yes, the same GoF pattern) independent of who triggered it. In the context of WPF, a Command is triggered by a control event (button click for example) with optional command parameters. Some of the aspects of the Commanding infrastructure are:

  1. Command source – The control that triggers the command. The source may disable itself if the command it can trigger cannot be triggered due to various reasons. You would have for sure noticed all the text editors disabling their Copy menu item, context menu and command/ribbon bar buttons when there is no text selected. Here, Copy is the command and the UI elements invoking Copy (menu item, command bar/ribbon button and context menu) are all command sources.
  2. Command target – The object/control the command execution logic depends on. In the text copy example above, the text box is the command target because the copy function works the properties (text selection) of the text box. If no text is selected, copy cannot work and hence the associated controls would be disabled.
  3. Command – The command itself with optional parameters required for executing the command logic. You might have also come across another term called ‘routed command’, which is nothing but a command with the ability to traverse up and down in the visual tree hierarchy (Routing is a topic by itself and won’t be discussed here).

Binding: A powerful feature to let UI controls automatically get data from an object and populate themselves instead of manually doing it. The binding infrastructure takes care of automatically updating the target whenever the source changes, vice versa or both (two-way binding). This is accomplished via event notification mechanism already available in .NET. The implying fact is that there should be a mechanism for the WPF’s binding engine to detect changes in the bound property data and pass those changes to the listeners. Binding can be used not just for properties but also for commands. The latter is required to delegate event handling logic from the UI to elsewhere (read ViewModel)! One important aspect of command binding is that it sets the binding scope which determines how far in the ancestor hierarchy a control can search for its command event handler.

These two form the backbone of the MVVM implementation, indeed. Despite a tiny description of Commands and Binding, both Silverlight and WPF have a strong infrastructure for Commands and Binding. I assume you have basic understanding of the both and the above only sets the context for MVVM.

I will get into some code and implement MVVM in WPF in my next due.

I am sure most of you would have seen tons of definitions, tutorials and examples of MVVM pattern and its context with respect to Windows Presentation Foundation (WPF) and Silverlight (a stripped down WPF for the internet browser environment). However, many people tell me that those examples don’t really help them understand the pattern fully well to use it in their applications or at least think about the pattern’s applicability in a given scenario. This post is an attempt to address this gap and demystify MVVM enough to start implementing it via code.

Like its ancestors – MVC, MVP/variations, MVVM pattern serves to a specific purpose: separating presentation (ASP.NET, Windows Forms, WPF and Silverlight) from data (business data such as order, customer, contact, etc.) and the logic of displaying it (responding to control events, displaying data using various controls, etc.). By this separation, another benefit that MVVM brings to the table is the testability of the presentation logic independent of the UI. This especially makes sense where UI designers and developers have to work on the same artifact to do their respective jobs and follow their own workflow. Imagine a UI designer working on an .aspx page and a developer on the page’s code-behind. The designer may do multiple iterations trying various design combinations, themes, reviewing it by the business, etc. while the developer wouldn’t really care about it. On the flip side, a developer would want to do unit testing, code analysis, bug fixing, etc. that the designer doesn’t care about. These two roles can work independently without challenges if there is a mechanism that helps seamlessly integrate their work at end with ease. MVVM is that mechanism, which addresses this exact problem with less or no effort!

Model: Data we intend to display in the UI via various controls. It could be any data source such as a WCF services, OData data provider, SQL Server and XML File.

View: The actual UI – web forms, Windows forms, WPF/Silverlight (consumer of data, the Model)

ViewModel (VM): The confusing piece in the pattern by its name for many people! VM acts as the data source for any component (consumer) that would be interested in the data exposed by the VM; yet it does not know anything about its consumer. The consumer could be a View (which is the case most of the time) or just anything that knows how to make the best out of VM’s data. As a matter of fact, the VM doesn’t care how the consumer would display the data (if it is a UI), use it or whatsoever. It is this fact that makes a VM testable without an UI via mocking. After testing, you just replace the mock with the actual UI and everything just works as intended.

Generally ViewModels are designed based on its consumer(s) data requirements (Model for the UI and hence the name ViewModel). For example, a VM for a dialog showing a list of products will have public properties and methods for product list (an ICollection may be?), sorting and filtering all for that dialog’s consumption.

Remember that there can be more than one consumer pulling data from a VM. You might have come across cases where a single VM provides data to more than one ViewModels. Who by the way provides data to a VM to serve to its consumer(s)? Model.

So, how MVVM fits into the WPF/Silverlight development? Stay tuned!

Microsoft has a WPF version of the DataGrid control outside its standard .NET Framework release 3.0+. This off-branch data grid is part of the WPF Toolkit maintained/released at CodePlex. However, a better one (in terms of features/ease of use, so far I have seen) is the Xceed XPF DataGrid Express Edition which has been around for quite sometime. It’s a free control (reg-ware) – but won’t be so after few weeks. If you want to explore its features, just take a look at their online demo (available via .xbap). Things I like about Xceed grid are its extreme rendering customization, multiple display styles (table, card, 3D & custom views) and theme-based eye-candy UI. It also supports standard grid features such as data editing, filtering, & grouping capabilities. And it allows exporting grid data to Excel (.xls) format – at least for now. Register yourself and download it from http://xceed.com/freegrid. [Registered for the free Xceed DataGrid for WPF and there’s only 22 days left to do it.http://xceed.com/freegrid]

It is very common in Windows applications to store application-wide data such as database connection strings, application title and folder path,etc that should be available for the duration of the application instance. The general strategy for storing such data is to have public classes with public properties/fields and access them from anywhere in the application. However, with Windows Presentation Foundation (WPF), the framework itself provides an application-wide “storage bag”, Application.Properties, that could be used for the very same purpose. This bag is an app-domain specific thread-safe key-value based IDictionary instance.


using System.Windows;
... ...
Application.Current.Properties["conStr"] = "my connection string";
... ...
string conStr = (string) Application.Current.Properties["conStr"]; // From anywhere in the application

Since the key value is of type object, a casting is required when retrieving the data from Application.Properties.