Browse Tag: wpf

Effectively debugging WPF MVVM applications

Being able to effectively debug any application is key to the success of an application.  Every developer, no matter how good they are or how long they have been writing code, introduces bugs.  Debugging is the process of identifying bugs and removing them.

WPF applications can be particularly hard to debug, if you are not using the correct tools.  This post attempts to help you utilise various free tools to help simplify the debugging process.

Binding Errors

Binding errors are very common in all WPF applications.  Binding errors are errors that occur when bindings in your view to properties on your view model to not match.  Take the following example;

The view;

<Window x:Class="DebuggingWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DebuggingWPF"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding DisplayProperty, Mode=Oneway}" />
    </Grid>
</Window>

And the view model;

public class MainWindowViewModel
{
    public string MyProperty
    {
        get { return "Hello, World!"; }
    }
}

What is the output of the above code? Are you expecting to see “Hello World” written out to the screen? Is this case, there is no output to the screen. So what went wrong?

Well on close inspection of the XAML and C# code, we can see that there is a mistake in our XAML. The binding expression points to a property called DisplayProperty, where as our view model does not have this property, it instead has a property called MyProperty.

This mistake was easy to identify because we only have a few lines of code. However, as soon as your application begins to get more complicated (that doesn’t take long when working with WPF :)) these sorts of problems become much harder to fix.

You may be wondering… why doesn’t Visual Studio throw an exception when a binding fails? Well apparently its an optimization (sorry I don’t have an citations for that claim!).

In any case, Visual Studio helps you out here. Simply open the Output Window (Debug > Windows > Output) and search for “BindingExpression”. You should find all the binding errors that occurred since your program started running;

Visual Studio Output Window

An alternative approach would be to make use of BindingSource.UpdateSourceExceptionFilter, which can be helpful when debugging individual properties. As far as I am aware, this type of approach cannot be used at a global level.

WPF Inspector

A tool I have found very helpful over the years is called WPF Inspector. I commonly refer to this tool as being the best and worst tool ever made, for lots of reasons … including;

  • Its unstable … it has a bad habit of crashing exactly when you find what you’re after
  • Its slow (sorry, but it just is)
  • The user interface is messy … the treeview on the left hand side is a hinderance
  • It allows other developers (malicious or not) to snoop at my code

However, there are also a lot of reasons in favour of using this tool;

  • It effectively visualises the Visual tree (the hierarchical structure of your XAML code)
  • It allows for on-the-fly tweaking of property values
  • It makes suggestions and recommendations on how your code can be improved and optimized
  • It allows me to snoop on other developers code!

To use WPF Inspector is straight forward. Run your application, and then run WPF Inspector. After what will feel like hours (but will actually more likely be just a few seconds) WPF Inspector will discover your application and you can click “Attach” to hook WPF Inspector onto your application. You can then start expanding out the nodes on the left hand side until you discover the elements that you are interested in. You can then tweak and change properties to your hearts content;

WPF inspector with some properties changed;
WPF Inspector

And the application after tinkering;

MainWindow WPF Inspector

Once you kill your application, all changes will be lost … so try to keep track of any changes you have made!

WPF Inspector is a very useful tool and will save you hours of time (and help your sanity as well!)

Reverse Engineering

Sometimes your code just refuses to work. A very good technique for helping to identify problems is by looking at your actual compiled source code. Opening a compile application and viewing the original source code is a process known as Reverse engineering.

There are many tools available to reverse engineer WPF applications (or indeed any .NET application) that hasn’t been obfuscated. My preferred tools of choice are DotPeek (free tool from JetBrains) and .NET Reflector by RedGate.

To reverse engineer (decompile) your application, simply fire up your tool of choice and browse to (or drag-and-drop) your applications executable file (exe) or any dynamically linked library (dll). Decompilation is usually very quick (but can take longer depending on the size of your application). You can then simply double click on any class that you want to look at;

Dot Peek

The code looks pretty much the same as how you saw it in Visual Studio.

This debugging technique is particularly helpful when you are trying to identify problems with third party tools. For example, it is common to use a tool such as PropertyChanged.Fody to inject INotifyPropertyChanged code automatically for you at compile time.

When change notifications are not pouring trickling through as you would expect, it can be helpful to decompile the code and check the class in question. If your automatic properties have not been expanded out and replaced with “compiler generated” properties with backing fields, you know that you have mis-configured the tool. Usually tweaking the tool then resolves the problem. This could literally save hours, if not days, of head scratching.

Summary

Some problems/bugs can be very difficult to track down in WPF applications. It is important to know what tools are available to help your quickly and easily resolve such issues.

Some tools include; the Output window in Visual Studio for identifying binding errors, WPF Inspector for tweaking and changing UI property values on-the-fly, and using decompilation tools to make sure that the compiled code matches what you expect.

If you found this blog post useful, please leave a comment below.

WPF Entity Framework Code First migrations

Recently I wrote a WPF application using Entity Framework Code First and released it into the wild.  Shortly after, the business requirements changed and I had to make changes to the model.  Thus, I was introduced to Code First migrations.

I did a lot of research on Code First migrations and could only really find the most simple of examples, and almost robotic documentation on MSDN that provided minimal help. This post aims to provide a clearer view on migrations, and how to properly create them.

Before we can start with migrations, we need to create our normal C# code and then add in Entity Framework using NuGet.  Once done, we can create our first migration and then explore a second migration.

The Code

The code is going to revolve around the common idea of customers and orders.

C# Code Structure

Code structure; An Order has a collection of Product and a Customer, the Customer has a CustomerName. Any properties that are marked as virtual are navigation properties, and are lazy loaded by Entity Framework at runtime.

public class Customer
{
    public int Id { get; set; }
    public int CustomerNameId { get; set; }
    public virtual CustomerName CustomerName { get; set; }
}

public class CustomerName
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual List<Product> Products { get; set; }
    public DateTime Placed { get; set; }
}

With the code structure in place, we can now introduce Entity Framework. Go ahead and use the package manager console, or the library package manager to install Entity Framework.

install-package EntityFramework

Enabling Migrations

Before enabling migrations, ensure that you have a DbContext class that contains a DbSet for use throughout the application;

public class Context : DbContext
{
    public DbSet<Order> Orders { get; set; }
}

Entity Framework uses the DbContext class to determine the structure of your database.

The key to making migrations work properly is to create an initial migration that will set up your database into its initial state when you deploy the application.

In the package manager console window, type the following command;

Enable-Migrations

You will notice that this process has has created a new folder (Migrations), and two new files; (Configuration.cs and InitialCreate, prefixed with a Date/Time stamp)

Entity Framework Initial Create

 

 

A word about seed data

At the time of writing, the current version of Entity Framework is 5.0.0.0 (public release). I have found that seed data does not behave in the way that I expect.

Open Configuration.cs and observe the seed data method;

protected override void Seed(CodeFirstMigrations.Context context)
{
    //  This method will be called after migrating to the latest version.

<pre><code>//  You can use the DbSet&amp;lt;T&amp;gt;.AddOrUpdate() helper extension method 
//  to avoid creating duplicate seed data. E.g.
//
//    context.People.AddOrUpdate(
//      p =&amp;gt; p.FullName,
//      new Person { FullName = &amp;quot;Andrew Peters&amp;quot; },
//      new Person { FullName = &amp;quot;Brice Lambson&amp;quot; },
//      new Person { FullName = &amp;quot;Rowan Miller&amp;quot; }
//    );
//
</code></pre>

}

Note that the comment clearly states that the method will be called directly after migrating to the latest version. I’ve found that, in reality, this method is called every time your application starts up. I suppose this is why the AddOrUpdate extension method was added, to prevent duplicate seed data.

Analysing the Visual Studio IntelliSense documentation closely, its pretty clear what this method expects for the first parameter;

AddOrUpdate Extension Method

CLICK IMAGE TO ENLARGE

For the AddOrUpdate method, we must pass in a parameter that will determine if the seed data is ADDED or UPDATED. Unfortunately, this doesn’t seem to work when passing in the primary key of the table (the Id property). For me, this is a major limitation and hopefully it will be resolved in future releases.

The solution here is to skip the seed data method altogether, and add some logic in the application start-up method to determine if the seed data needs to be added or updated.

The final step is to update your initializer to use the MigrateDatabaseToLatestVersion database initializer;

public class Initializer : MigrateDatabaseToLatestVersion<Context, Configuration>
{
}

You can now deploy your application to your customers, knowing that when the customer runs the program for the first time, the database will be created as you expect and and seed data will also be added.

Your second migration

Your second migration now should be straight forward. Simply go ahead and make the desired changes to your model. We will add the following class;

[Table("CreditCardInformation")]
public class CreditCardInformation
{
    public int Id { get; set; }
    public CreditCardType CreditCardType { get; set; }
    public string CreditCardNumber { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

Note that the Table attribute used above is to ensure that Entity Frameworks pluralisation service doesn’t incorrectly name our table. Add a CreditCardInformation property to Customer.

public class Customer
{
    public int Id { get; set; }
    public int CustomerNameId { get; set; }
    public virtual CustomerName CustomerName { get; set; }
    public virtual CreditCardInformation CreditCardInformation { get; set; }
}

Now you are ready to create a migration. You can name the migration simply by passing the desired name in as a parameter.

Add-Migration AddCreditCardInformation

Your migration will look something like this;

public partial class AddCreditCardInformation : DbMigration
{
    public override void Up()
    {
        CreateTable(
            &quot;dbo.CreditCardInformation&quot;,
            c =&gt; new
                {
                    Id = c.Int(nullable: false, identity: true),
                    CreditCardType = c.Int(nullable: false),
                    CreditCardNumber = c.String(),
                    StartDate = c.DateTime(nullable: false),
                    EndDate = c.DateTime(nullable: false),
                })
            .PrimaryKey(t =&gt; t.Id);

<pre><code>    AddColumn(&amp;quot;dbo.Customers&amp;quot;, &amp;quot;CreditCardInformation_Id&amp;quot;, c =&amp;gt; c.Int());
    AddForeignKey(&amp;quot;dbo.Customers&amp;quot;, &amp;quot;CreditCardInformation_Id&amp;quot;, &amp;quot;dbo.CreditCardInformation&amp;quot;, &amp;quot;Id&amp;quot;);
    CreateIndex(&amp;quot;dbo.Customers&amp;quot;, &amp;quot;CreditCardInformation_Id&amp;quot;);
}

public override void Down()
{
    DropIndex(&amp;quot;dbo.Customers&amp;quot;, new[] { &amp;quot;CreditCardInformation_Id&amp;quot; });
    DropForeignKey(&amp;quot;dbo.Customers&amp;quot;, &amp;quot;CreditCardInformation_Id&amp;quot;, &amp;quot;dbo.CreditCardInformation&amp;quot;);
    DropColumn(&amp;quot;dbo.Customers&amp;quot;, &amp;quot;CreditCardInformation_Id&amp;quot;);
    DropTable(&amp;quot;dbo.CreditCardInformation&amp;quot;);
}
</code></pre>

}

Entity Framework gives us the ability to roll back a migration if needed. When a roll back occurs, the Down method on the migration is called and the changes are reverted.

To perform a rollback, simply run the following command;

Update-Database -TargetMigration:"NameOfMigrationToRollBackTo"

If you try to run the application at this time, you will get the following error message;

The model backing the 'Context' context has changed since the database was created.
Consider using Code First Migrations to update the database.

This is because you need to commit the changes to your database, you can do this using the following command;

Update-Database

Run the application again, and all should work as you expect.

Summary

Entity Framework Code First migrations are an exciting and powerful new feature that will dramatically simplify your deployment and update process. The MigrateDatabaseToLatestVersion database initialization strategy will take care of automatically updating your database to the most current version, and can even help with seed data. Seed data is made easy thanks to a new AddOrUpdate extension method, but is limited in that you cannot use the table primary key as the identifier.

Using StructureMap setter injection to inject repositories into your View Model

This short post is a follow on from an earlier series of posts that discussed how to achieve MVVM purity in WPF using Structure Map.  You may want to check out those posts first before reading this post.  However, if you just generally want to know how to do setter injection using Structure Map, you are in the right place!

A Scenario

It is very common in modern applications to have a repository that does the job of retrieving and saving data from/to your database.

Your repository may look like this;

public interface IRepository&lt;T&gt;
{
    int Count { get; }
}

public class CustomersRepository : IRepository&lt;Customer&gt;
{
    private readonly Random _random = new Random();

<pre><code>public int Count
{
    get { return _random.Next(3, 10); }
}
</code></pre>

}

In the above sample we are simulating retrieving the number of customers that currently exist in our database.

Our view model logic may look something like this;

public class ChildViewModel : BaseViewModel, IChildViewModel
{
    public ChildViewModel(IChildView view, IContainer container)
        : base(view, container)
    {
    }

<pre><code>public IRepository&amp;lt;Customer&amp;gt; CustomersRepository { get; set; }

public int CustomerCount { get; set; }

public override void Load()
{
    CustomerCount = CustomersRepository.Count;
}
</code></pre>

}

When the view model has finished loading, we want to retrieve the number of customers from the repository and display this number to the user. How do we get an instance of CustomersRepository?

Well there are two approaches, this is the first;

public override void Load()
{
    CustomersRepository = ObjectFactory.GetInstance<IRepository<Customer>>();
    CustomerCount = CustomersRepository.Count;
}

You can use the static ObjectFactory.GetInstance() method to get an instance of the repository and set the public property to that value. Don’t get me wrong, this approach works… but it is widely considered to be an anti-pattern.

The second approach is to use setter injection, which basically means that StructureMap will inject a value for that property automatically for you at runtime, so that you don’t have to worry about it.

Bootstrapper

All StructureMap based applications begin with a bootstrapper. Your bootstrapper class will typically be a public static class that calls the ObjectFactory.Initialise() method passing an IInitializationExpression object.

We will need to add our repository to the container so that it can be used thoughout the application;

public static class Bootstrapper
{
    public static void Initialise()
    {
        ObjectFactory.Initialize(OnInitialise);
    }

<pre><code>private static void OnInitialise(IInitializationExpression x)
{
    //Omitted for brevity

    //Add the repository
    x.For&amp;lt;IRepository&amp;lt;Customer&amp;gt;&amp;gt;().Use&amp;lt;CustomersRepository&amp;gt;();

    //Tell StructureMap to automatically inject an instance, whenever it comes across a public property of type IRepository&amp;lt;Customer&amp;gt;
    x.SetAllProperties(y =&amp;gt; y.OfType&amp;lt;IRepository&amp;lt;Customer&amp;gt;&amp;gt;());
}
</code></pre>

}

To make StructureMap take care of the setter injection for us, we simply needed to call the SetAllProperties method.

When StructureMap resolves an instance of our view model (or any class for that matter), it inspects it, identifies all the public properties in that class, and looks inside the container to see if it has any matching instances. If it does, it simply injects them for us.

Summary

We can use StructureMap to inject instances of objects into the public properties on our view models simply by calling the SetAllProperties method when initialising the container and telling it what type we want injecting.

WPF MVVM IoC containers – Part 2 of 2

The ultimate goal of MVVM is to achieve true separation of concerns, meaning that the various elements of your project know nothing about each other.  It’s virtually impossible to achieve this in an elegant way in WPF without some outside help.

You are reading the second part of this blog post where we will discuss how to use an IoC container properly in a WPF MVVM application.  It is assumed you have either read the first post, or are familiar with the concept of IoC/dependency injection with StructureMap.

Part 0

It’s worth noting just before we get started that you will need to invest a little time to get this set up initially.  That investment will pay off almost immediately as your application begins to scale.

Please take the time to, if you haven’t already, install PropertyChanged.Fody and StructureMap from NuGet.

Core Classes

Start by creating some core classes for use within the rest of your application.  Getting these in a good state early will make architecting the rest of the application a lot easier.

I like to have all my classes inherit from a class called BaseNotification, so that I (thanks to PropertyChanged.Fody) get all the change notification functionality added for free to all my derived classes.

public class BaseNotification : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Before we can continue, we must add a couple of interfaces to our Core folder. An interface is needed for the actual View (IView) and the View Model (IViewModel) so that we can maintain loose coupling from the Main Window (described later).

public interface IView
{
    object DataContext { get; set; }
}

public interface IViewModel
{
    IView View { get; set; }
}

Note that each view model will have a reference back to the actual view (which is a user control) so as to make finding controls in the visual tree possible, freeing up the parameter on our delegate/relay commands.

Now we need to create our BaseViewModel. Add the following code;

public class BaseViewModel : BaseNotification, IViewModel
{
    public BaseViewModel(IView view, IContainer container)
    {
        View = view;
        View.DataContext = this;

        Container = container;
    }

    public IContainer Container { get; set; }

    public IView View { get; set; }
}

Lets take a second to review what we have here. The constructor is very important as whatever parameters we defined here are going to be injected automatically by the IoC container. We want to pass in an instance of the actual view and a reference back to the IoC container itself. Why? because this gives a means for derived view models to access instances of objects without having to use ObjectFactory.GetInstance, which (as previously discussed) is an anti-pattern. Inside the constructor we set the views data context, which is itself, so as to make data binding possible. This removes the direct relationship between the view and the view model, whilst keeping our code neat, maintainable, and adherent to the DRY principle.

Now over to the window. In this tutorial we are only going to have a single Window, but typically in larger applications you will have multiple windows so its a good idea to get off on the right foot.

We need 2 new interfaces, IWindow and IWindowViewModel. IWindow will represent the Window (MainWindow) and IWindowViewModel is for the windows view model.

public interface IWindow
{
    object DataContext { get; set; }
}

public interface IWindowViewModel
{
    IWindow Window { get; set; }
}

You may have noticed that this is the same set-up as the IView and IViewModel interfaces. A few seconds ago I was telling you to avoid repetition! What gives?! Well over time the Window and your view models will naturally evolve in different directions, so its a good idea to keep them independent of each other from the start.

Now over to the BaseWindowViewModel class, which will act as the data context for your windows;

public class BaseWindowViewModel : BaseNotification, IWindowViewModel
{
    public BaseWindowViewModel(IWindow window, IContainer container)
    {
        Window = window;
        Window.DataContext = this;

        Container = container;
    }

    public IView View { get; set; }

    public IContainer Container { get; set; }

    public IWindow Window { get; set; }

    protected void ShowView<T>() where T : IViewModel
    {
        View = Container.GetInstance<T>().View;
    }
}

Whilst the BaseWindowViewModel is similar to the BaseViewModel class, there are a few subtle differences here. The window is going to display your view within itself. To make this possible, we need a View property, which can be of type IView as all our views implement this interface. We also have a ShowView method, which retrieves an instance of the view from the container, using the type parameter passed in.

So far our code is looking clean and crisp, without a concrete class in sight. This will make unit testing a breeze later on, as mocking/stubs/fakes will now be a lot easier.

Creating a window

Now that we have the core pieces in place, we can turn our attention to creating a window. The window in this example is going to display a couple of views (one at a time) and navigation will be achieved via some buttons.

This is what we’re aiming for;

WPF MVVM Structure Map Main Window

When a button is clicked, the corresponding view is displayed whilst displaying details about its data context.

Start by adding two interfaces;

public interface IMainWindow : IWindow
{
}

public interface IMainWindowViewModel : IWindowViewModel
{
}

No need to add additional properties at this stage, but you might want to add them going forward if you are planning on having multiple concrete classes that implement these interfaces, or if you are unit testing.

Next, head over to the MainWindow.xaml.cs file and make sure it implements the IMainWindow interface;

public partial class MainWindow : Window, IMainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Now just add the MainWindowViewModel class, and add the following code;

public class MainWindowViewModel : BaseWindowViewModel, IMainWindowViewModel
{
    public MainWindowViewModel(IMainWindow window, IContainer container)
        : base(window, container)
    {
        ShowFirstChildCommand = new DelegateCommand<object>(OnShowFirstChild);
        ShowSecondChildCommand = new DelegateCommand<object>(OnShowSecondChild);
        ExitCommand = new DelegateCommand<object>(OnExit);
    }

    public DelegateCommand<object> ShowFirstChildCommand { get; set; }

    public DelegateCommand<object> ShowSecondChildCommand { get; set; }

    public DelegateCommand<object> ExitCommand { get; set; }

    private void OnExit(object obj)
    {
        Application.Current.Shutdown();
    }

    private void OnShowSecondChild(object obj)
    {
        ShowView<ISecondChildViewModel>();
    }

    private void OnShowFirstChild(object obj)
    {
        ShowView<IChildViewModel>();
    }
}

Note if you have not previously encountered the DelegateCommand, there are lots of implementations available online. You can download the version I have used here.

The constructor here is of critical importance to the whole concept. If you are using a refactoring tool such as ReSharper, please be sure to double check that the constructors first parameter is of type IMainWindow and not IWindow. ReSharper notices that you can use the more generic IWindow, as no properties from IMainWindow are used on the base class. Doing this, however, will result in StructureMap not knowing which type it actually needs to inject.

As we added the logic for displaying the actual view in our BaseWindowViewModel, we simply need to call ShowView() passing in the type of the view model we actually want to display. (The view that corresponds to the aforementioned view model).

Finally, open MainWindow.xaml and replace the existing Grid with the Grid below;

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
        
    <ContentControl Content="{Binding View}" 
                    Margin="10"/>
        
    <StackPanel Orientation="Horizontal"
                Grid.Row="1"
                VerticalAlignment="Center"
                HorizontalAlignment="Center">
            
        <Button Content="Show First Child"
                Command="{Binding ShowFirstChildCommand}"/>
            
        <Button Content="Show Second Child"
                Command="{Binding ShowSecondChildCommand}"/>
            
        <Button Content="Exit"
                Command="{Binding ExitCommand}"/>
            
    </StackPanel>
</Grid>

We will display our view (which is simply a user control) using a ContentControl. You can make this as elaborate as you like!

Creating a view

So far we have created our core classes, and created a window. Next we need to add a view to actually display within our window.

Add a new user control, call it ChildView.xaml and a matching IChildView.cs interface. Ensure that the user control implements the IChildView interface, and the IChildView interface implements IView… as shown below;

public interface IChildView : IView
{
}

public partial class ChildView : UserControl, IChildView
{
    public ChildView()
    {
        InitializeComponent();
    }
}

Next, create the ChildViewModel and IChildViewModel classes, as before ensuring that ChildViewModel implements IChildViewModel and IChildViewModel implements IView.

public interface IChildViewModel : IViewModel
{
}

public class ChildViewModel : BaseViewModel, IChildViewModel
{
    public ChildViewModel(IChildView view, IContainer container)
        : base(view, container)
    {
    }
}

As your ChildViewModel is going to inherit from BaseViewModel, as before you will be required to call the constructor of that class. Please ensure you take a second to double check that the view parameter is of type IChildView and not IView.

Now as an almost final step, go ahead and repeat this step. This time call it SecondChildView.

Tying it all together

First and foremost, we need to make sure that our IoC container knows about the windows and views that we have just added. Open up (or create) the bootstrapper that we created in the first part of this tutorial and add the following code.

Note that I have refactored out the lambda expression for simplicity.

public static class Bootstrapper
{
    public static void Initialise()
    {
        ObjectFactory.Initialize(OnInitialise);
    }

    private static void OnInitialise(IInitializationExpression x)
    {
        x.For<IMainWindow>().Singleton().Use<MainWindow>();
        x.For<IMainWindowViewModel>().Singleton().Use<MainWindowViewModel>();

        x.For<IChildView>().Use<ChildView>();
        x.For<IChildViewModel>().Use<ChildViewModel>();

        x.For<ISecondChildView>().Use<SecondChildView>();
        x.For<ISecondChildViewModel>().Use<SecondChildViewModel>();
    }
}

Notice in the above code, I have included the Singleton() method for the MainWindow and MainWindowViewModel types. This is because, if there are any subsequent requests for an instance of these types, the same instance will get served up every time.

Finally

All that is left is to retrieve an instance of MainWindow from the container and serve it up to the user. Don’t forget to initialise the bootstrapper in the application constructor.

public App()
{
    Bootstrapper.Initialise();
}

protected override void OnStartup(StartupEventArgs e)
{
    IMainWindowViewModel window = ObjectFactory.GetInstance<IMainWindowViewModel>();
    MainWindow = (MainWindow) window.Window;
    MainWindow.ShowDialog();
}

For the sake of completeness, I added a Resource Dictionary with the below style to set some sizing on the MainWindow buttons;

<Style TargetType="{x:Type Button}">
    <Setter Property="Width"
            Value="125" />
    <Setter Property="Height"
            Value="30" />
    <Setter Property="Margin"
            Value="5" />
</Style>

Summary

IoC containers provide a simple and elegant solution to doing dependency injection in a large WPF MVVM application. IoC containers are also responsible for managing the lifetime of our windows/views/view models. Using an IoC container also has a positive side effect of forcing you to structure your classes in a way that promotes unit testing.

Download source code

WPF MVVM IoC containers – Part 1 of 2

The ultimate goal of MVVM is to achieve true separation of concerns, meaning that the various elements of your project know nothing about each other.  It’s virtually impossible to achieve this in an elegant way in WPF without some outside help.

For example, how to you tie the view model to a view?  Here are some ideas that spring to mind;

1) You could set the data context directly in the view;

<Window.DataContext>
    <local:MainWindowViewModel />
</Window.DataContext>

2) You could set the data context in the views code behind file;

public partial class MainWindow : BaseWindow
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

3) Or you could set the data context when the view is instantiated;

View = new MainWindow();
View.DataContext = new MainWindowViewModel();

View.ShowDialog();

The problem with the first approach is that you are creating a relationship between the view and the view model. Admittedly its a dynamic relationship, but, a relationship none the less.  This is contrary to the MVVM concept.

The second approach adds code behind, which is basically banned in MVVM, and the third approach would result in your writing lots of code that will become unmaintainable over time.

Dependency Injection

Dependency injection is the idea that instances of required objects will be passed in to the class at some point.  I say some point because this could be via the constructor or through lookups (usually on getters/setters of public properties).

Constructor injection;

public class MainWindowViewModel
{
    public MainWindowViewModel(Window mainWindow)
    {
        MainWindow = mainWindow;
    }

    public Window MainWindow { get; set; }
}

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        MainWindow = new MainWindow();
        MainWindow.DataContext = new MainWindowViewModel(MainWindow);
        MainWindow.ShowDialog();
    }
}

Constructor injection is a step in the right direction, but taking this approach will become unmaintainable over time as the application grows.  This is where IoC containers really come into their own.

A better way – Inversion of Control containers

Inversion of Control (IoC) containers take over the responsibility of two important aspects of your code; managing instances of your views/view models, and performing dependency injection automatically.

There are many IoC containers available to use within your .NET applications.  I personally have worked directly with two; the Unity Application Block from the Microsoft Patterns and Practices library, and Structure Map.  There are lots of blog posts that compare the intricacies of these containers, and many more, so I won’t try and re-invent the wheel.  There is a very good post on ElegantCode.com that goes in to a good level of detail.

For the remainder of this blog post and the next in the series, we will focus on Structure Map – as its lightweight, quick to get started with, and highly configurable.

Structure Map – A crash course

Getting started with Structure Map in Visual Studio 2010/2012 has never been easier, thanks to NuGet.  Fire up the package manager console and run the following command;

install-package StructureMap

This will go and fetch the latest version of StructureMap, and add the appropriate references to your project (StructureMap.dll).

Bootstrapper

Start by creating a bootstrapper class.  A bootstrapper class is just a simple class that will initialise our IoC container, and tell it about the types in our project.

public static class Bootstrapper
{
    public static void Initialise()
    {
        ObjectFactory.Initialize(x =>
        {
            x.For<IMainWindow>().Use<MainWindow>();
            x.For<IMainWindowViewModel>().Use<MainWindowViewModel>();
        });
    }
}

Structure map has a kind of fluent API that basically describes to us what its doing. When a request is made for an instance of IMainWindow, the concrete type MainWindow is served up. Same goes for our view model.  Whenever you want instances of an object to be automatically managed for you, you must add them to this initialisation method.

Lets revisit the constructor injection example from earlier. First though, we need to make sure we call the Initialise() method on our bootstrapper. A good place for this would be in the constructor for our application.

public App()
{
    Bootstrapper.Initialise();
}

Now, instead of creating instances of our objects directly, we make a call to the container and request an instance.

protected override void OnStartup(StartupEventArgs e)
{
    IContainer container = ObjectFactory.Container;

    MainWindow = (Window)container.GetInstance<IMainWindow>();
    MainWindow.DataContext = container.GetInstance<IMainWindowViewModel>();
    MainWindow.ShowDialog();
}

ObjectFactory is simply a static wrapper around our container.  Its important to note that accessing instances of objects via the ObjectFactory within your view models is considered an anti-pattern.  We will look at how to avoid this in the subsequent post.

Summary

In this short post we have discussed what Dependency Injection is, and how a Inversion of Control (IoC) container goes a step further. An IoC container manages the instances of our objects automatically for us, and can take responsibility for injecting instances of any object that it knows about into the constructor of our view models.

In the next post, we will look at fully implementing IoC containers in a WPF MVVM application.

Download source code

Entity Framework Code First In 15 Minutes

Entity Framework is an Object Relational Mapper (ORM), created by Microsoft and built on top of the popular ADO.NET framework.  Entity framework was first released in the second half of 2008.  In 2011, with the release of version 4.1, a new feature was introduced… known as “Code First”.

Code first allows us to write code without having to care (to a certain extent) about the make-up of the database, its tables and their relationships.  The idea is that Entity Framework figures all this out for us, and it does a pretty good job!  Entity Framework code first is designed around the “convention over configuration” principal, meaning as long as things are named in a consistent way your code should “just work” with very little effort.  If its not possible to write your code in a way that Entity Framework understands, it is possible to tell Entity Framework about your model using attributes, the Fluent API, or a combination of both.

Adding Entity Framework to your project

The quickest way to add Entity Framework to your project is using the Package Manager Console (NuGet). In Visual Studio, click “View > Other Windows > Package Manager Console”, and type the following command;

Install-Package EntityFramework

Install Package

This process will add all the appropriate references to your project.

Super Quick Walk-through

This tutorial aims to get you up and running in about 15 minutes.  We will create a very simple application, which has a WPF front end and an Entity Framework back end, based around the idea of customers, addresses and orders.  Every customer will have an address and optionally they can have orders.

So lets get to it, the clock is ticking.  Create a new WPF project, call it SuperQuick.

SuperQuick

Add the following classes to your project;

  • Address.cs
  • Customer.cs
  • MainWindowViewModel.cs (Model class for our view, as per the MVVM specification)
  • SuperQuickContext.cs (This will be our database context)
  • SuperQuickInitializer.cs (This will define the database initialization strategy)

Add the following code to Customer.cs

public class Customer
{
    public Customer()
    {
        Orders = new List&lt;Order&gt;();
    }

<pre><code>public int Id { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public Address Address { get; set; }

public virtual List&amp;lt;Order&amp;gt; Orders { get; set; }

public override string ToString()
{
    return string.Format(&amp;quot;{0}, {1}&amp;quot;, LastName.ToUpper(), FirstName);
}
</code></pre>

}

Lets take a moment out to look at this code.  Customer will be mapped to its own table in your database, and Id will be considered the primary key.  Notice that we have a property called Address of type Address.  Address is a complex type, meaning it consists of multiple fields/properties.

How will this be mapped to the database?  Well Entity Framework will analyse the class and create a column for each publicly accessible property.  The database table will eventually look like this (once we flesh out the Address class);

Complex Type

Notice the naming of each column.  This is significant because Entity Framework uses the column name to match the value back to each property on your class.  Also note the data type for each column.  You can explicitly dictate what data type you want to use (perhaps NVARCHAR(255) for a string no longer than 255 characters) using a combination of attributes and the fluent API.  We may cover these topics in more detail in another blog post.

Also notice that we have a List of type Order placed by the company.  This property basically has a one to many relationship with customer, as a customer can have none, one, or many orders.  The property is marked as virtual so that Entity Framework can create a dynamic proxy for the property, which enables for lazy loading and change tracking.  This may, when used right, improve performance by only retrieving data when needed.

Add the following to Address.cs

public class Address
{
    public string Line1 { get; set; }

<pre><code>public string Line2 { get; set; }

public string Town { get; set; }

public string PostCode { get; set; }

public override string ToString()
{
    return string.Format(&amp;quot;{0}n{1}n{2}n{3}&amp;quot;, Line1, Line2, Town, PostCode);
}
</code></pre>

}

Next, we need to create a database context (DbContext).  We will use the DbContext to tell Entity Framework about our model classes.

Add the following code to SuperQuickContext.cs

public class SuperQuickContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

Notice that we haven’t created a DbSet for the Address or Order classes?  Well Entity Framework detects that Customer has a dependency on these classes, so it just includes them automatically for us.  Adding a DbSet for the Order class wouldn’t affect the model, but adding a DbSet for Address would result in an error, because Address doesn’t have a suitable primary key property.

Next, we need to decide which database initialization strategy we want to use.  This tells Entity Framework what to do with our database if our model changes (or the database doesn’t exist).  When developing our project, its fine to use the  DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways strategy.  When moving to a release, you may want to disable database initialization and make use of a feature of Entity Framework called “Code First Migrations” … or you will lose all of your data!

For us, there is no need to recreate the database unless the model changes, so we will use DropCreateDatabaseIfModelChanges.

We could override the OnStartup method in App.xaml.cs and set our initializer;

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

<pre><code>Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
</code></pre>

}

But actually this is not quite what we want. We want to introduce seed data to set some “default values” in our database when it gets created or dropped and re-created.

Add the following code to SuperQuickInitializer.cs

public class SuperQuickInitializer : DropCreateDatabaseIfModelChanges&lt;SuperQuickContext&gt;
{
    protected override void Seed(SuperQuickContext context)
    {
        //Create some dummy data
        Address addressOne = new Address
        {
            Line1 = &quot;Address Line 1&quot;,
            Line2 = &quot;Address Line 2&quot;,
            PostCode = &quot;AB1 ABC&quot;,
            Town = &quot;The Town&quot;
        };

<pre><code>    Address addressTwo = new Address
    {
        Line1 = &amp;quot;Second Address 1&amp;quot;,
        Line2 = &amp;quot;Second Address 2&amp;quot;,
        PostCode = &amp;quot;DE2 DEF&amp;quot;,
        Town = &amp;quot;Second Town&amp;quot;
    };

    Customer customerOne = new Customer
    {
        Address = addressOne,
        FirstName = &amp;quot;Jon&amp;quot;,
        LastName = &amp;quot;Preece&amp;quot;,
    };

    Customer customerTwo = new Customer
    {
        Address = addressTwo,
        FirstName = &amp;quot;Mike&amp;quot;,
        LastName = &amp;quot;Smith&amp;quot;
    };

    Order order = new Order
    {
        Amount = 10,
        Item = &amp;quot;Mouse&amp;quot;
    };

    Order orderTwo = new Order
    {
        Amount = 20,
        Item = &amp;quot;Keyboard&amp;quot;
    };

    Order orderThree = new Order
    {
        Item = &amp;quot;Monitor&amp;quot;,
        Amount = 100
    };

    customerOne.Orders.Add(order);
    customerTwo.Orders.AddRange(new[] { orderTwo, orderThree });

    //Add to the context
    context.Customers.Add(customerOne);
    context.Customers.Add(customerTwo);

    //Save changes
    context.SaveChanges();
}
</code></pre>

}

Note we have inherited from DropCreateDatabaseIfModelChanges so that we get all the behaviour, whist being able to insert our own seed data.

Now flip back over to App.xaml.cs and add the following code;

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

<pre><code>Database.SetInitializer(new SuperQuickInitializer());
</code></pre>

}

User Interface

We’re just about done with setting up our model, so now lets turn our attention to the user interface.  First set the MainWindow data context to an instance of MainWindowViewModel. Switch over to MainWindow.xaml and add the following code underneath the opening Window tag; (be sure to add an xml namespace, called local)

<Window.DataContext>
    <local:MainWindowViewModel />
</Window.DataContext>

Replace the existing Grid control with the following code;

<Grid>
    <ScrollViewer>
        <ItemsControl ItemsSource="{Binding Customers}"
                        AlternationCount="2"
                        ScrollViewer.CanContentScroll="True">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel x:Name="Main">
                        <TextBlock Text="{Binding}"
                                    FontWeight="Bold"
                                    FontSize="14"
                                    Padding="10,10,0,0" />
                        <TextBlock Text="{Binding Address}"
                                    FontSize="12"
                                    Padding="10,0,0,10" />
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Orders:"
                                        Margin="0,0,5,0"
                                        Padding="10,0,0,10"
                                        FontWeight="Bold" />
                            <TextBlock Text="{Binding Orders.Count}" 
                                        Padding="0,0,0,10"/>
                        </StackPanel>
                    </StackPanel>
                    <DataTemplate.Triggers>
                        <Trigger Property="ItemsControl.AlternationIndex"
                                    Value="0">
                            <Setter TargetName="Main"
                                    Property="Background"
                                    Value="#220000FF" />
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex"
                                    Value="1">
                            <Setter TargetName="Main"
                                    Property="Background"
                                    Value="White" />
                        </Trigger>
                    </DataTemplate.Triggers>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</Grid>

This will display our customers, their address, and the number of orders they have placed.

To satisfy the XAML, we need to add some code to our view-model … as follows;

public ObservableCollection<Customer> Customers { get; set; }

Finally, we need to populate the ObservableCollection with code from our database. Add the following constructor to the class;

public MainWindowViewModel()
{
    var context = new SuperQuickContext();

<pre><code>Customers = new ObservableCollection(context.Customers);
</code></pre>

}

 

Summary

In this super quick introduction, we have seen how easy it is to create an application that persists data to a database using Entity Framework. We have touched on topics such as complex types, navigation properties database initializers. Subsequent posts will cover more advanced topics such as data annotations, the Fluent API, and code first migrations.

WPF MVVM For WinForms Devs – Part 5/5

The purpose of this series of tutorials is to introduce the Model-View-ViewModel (MVVM) design pattern, and look at how to quickly and simply implement it in a Windows Presentation Foundation (WPF) application. This series is targeted at developers of all levels, but especially at developers who are looking to make the transition from Windows Forms to WPF.

This final part of the series assumes you have at least read the previous parts, or have a good working knowledge of WPF and the MVVM design pattern.

User Controls

User controls are controls that you have created for use throughout your application. Often user controls are a composite of existing WPF controls, pieced together to simplify code, improve maintainability by improving code reuse, and provide a consistent look and feel throughout your application.

In this tutorial we are going to look at how to create a date time picker as a single, unified control that accepts a DateTime object as its value.

Custom Date Picker

To make this possible, we will need to create the following;

  • Resource dictionary to store all our styles/layout behaviour (called CustomControls.xaml)
  • A class for the control behavioural logic itself (called CustomDateTimePicker.cs
  • A view and a view model for displaying and binding (called MainWindow.xaml and MainWindowViewModel.cs)

Go ahead and add the above files into your project. If you followed on from earlier parts of this post, simply stick with your existing project.

CustomDatePicker behavioural logic

Our user control is going to be a composite control that consists of a DatePicker and a ComboBox (for the times, shown in 30 minute intervals. When we provide a DateTime object to the control, it is going to split the values and display them accordingly. Likewise, when the user selects a date/time, that value is going to be reflected back to our view model.

Start by firing up the CustomDatePicker.cs file, make sure its public and inherits from UserControl. Also, ensure that the class implements the INotifyPropertyChanged interface, to ensure change notifications are created when appropriate.

public class CustomDateTimePicker : UserControl, INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

<pre><code>public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

#endregion
</code></pre>

}

Start by adding a dependency property to the control, called SelectedDateTime. This will be the property that we will bind to on our view model, to both provide data to the control, and receive data from it;

#region Dependency Properties

public static readonly DependencyProperty SelectedDateTimeProperty =
    DependencyProperty.Register("SelectedDateTime", typeof(DateTime), typeof(CustomDateTimePicker), new PropertyMetadata(GetDefaultDateTime(), Changed));

public DateTime SelectedDateTime
{
    get { return (DateTime)GetValue(SelectedDateTimeProperty); }
    set { SetValue(SelectedDateTimeProperty, value); }
}

#endregion

Amongst other things, a dependency properties accept bindings and raise their own change notifications (normal properties do not).

Next we are going to need some private methods/members.

#region Private Members

private DateTime _date;
private bool _isInternallyChanging;
private TimeSpan _time;

#endregion

#region Private Methods

private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    CustomDateTimePicker picker = d as CustomDateTimePicker;
    if (picker == null)
        return;

<pre><code>if (picker._isInternallyChanging)
    return;

DateTime dateTime = (DateTime)e.NewValue;

picker.Date = dateTime.Date;
picker.Time = TimeSpan.Parse(dateTime.ToString(&amp;quot;HH:00&amp;quot;));
</code></pre>

}

private static ObservableCollection&lt;TimeSpan&gt; GetDefaultTimes()
{
    ObservableCollection&lt;TimeSpan&gt; times = new ObservableCollection&lt;TimeSpan&gt;();

<pre><code>DateTime today = DateTime.Today;
for (DateTime time = today.AddHours(0); time &amp;lt; today.AddHours(24); time = time.AddMinutes(30))
{
    times.Add(time.TimeOfDay);
}

return times;
</code></pre>

}

private static DateTime GetDefaultDateTime()
{
    return DateTime.Parse(DateTime.Now.ToString(&quot;dd-MMM-yyyy HH:00&quot;));
}

private void SetSelectedDate()
{
    _isInternallyChanging = true;
    SelectedDateTime = new DateTime(Date.Year, Date.Month, Date.Day, Time.Hours, Time.Minutes, Time.Seconds);
    _isInternallyChanging = false;
}

#endregion

The static method Changed is a call back method that gets raised whenever the value of the dependency property gets changed. We need to keep an eye on the new value, so that whenever it changes (as long as we arent making the changes internally), we can split the value and display each part in the corresponding control. The other private methods are helper methods to populate the times combo box, get the selected date etc.

Finally, add the constructor and the public properties to ensure that the times combo box is populated and to ensure that there is a property for each control to bind to (Date and Time split parts);

#region Constructor

public CustomDateTimePicker()
{
    Times = GetDefaultTimes();
}

#endregion

#region Public Properties

public DateTime Date
{
    get { return _date; }
    set
    {
        _date = value;
        SetSelectedDate();
    }
}

public TimeSpan Time
{
    get { return _time; }
    set
    {
        _time = value;
        SetSelectedDate();
    }
}

public ObservableCollection<TimeSpan> Times { get; set; }

#endregion

The controls user interface

All we need to do now, in relation to the code for our custom control, is to design its visual appearance. This is achieved by using a style and control template.

First things first, make sure that the resource dictionary you have added in reference in the App.xaml file;

<Application.Resources>
    <ResourceDictionary Source="CustomControls.xaml" />
</Application.Resources>

Add the following code to your resource dictionary;

&lt;Style TargetType=&quot;{x:Type local:CustomDateTimePicker}&quot;&gt;
    &lt;Setter Property=&quot;Width&quot;
            Value=&quot;300&quot; /&gt;
    &lt;Setter Property=&quot;HorizontalAlignment&quot;
            Value=&quot;Left&quot; /&gt;
    &lt;Setter Property=&quot;Template&quot;&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType=&quot;{x:Type local:CustomDateTimePicker}&quot;&gt;

<pre><code>            &amp;lt;Grid&amp;gt;
                &amp;lt;Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;ColumnDefinition /&amp;gt;
                    &amp;lt;ColumnDefinition Width=&amp;quot;10&amp;quot; /&amp;gt;
                    &amp;lt;ColumnDefinition /&amp;gt;
                &amp;lt;/Grid.ColumnDefinitions&amp;gt;

                &amp;lt;DatePicker SelectedDate=&amp;quot;{Binding Date, RelativeSource={RelativeSource TemplatedParent}}&amp;quot; /&amp;gt;

                &amp;lt;ComboBox SelectedItem=&amp;quot;{Binding Time, RelativeSource={RelativeSource TemplatedParent}}&amp;quot;
                            ItemsSource=&amp;quot;{Binding Times, RelativeSource={RelativeSource TemplatedParent}}&amp;quot;
                            Grid.Column=&amp;quot;2&amp;quot; /&amp;gt;

            &amp;lt;/Grid&amp;gt;

        &amp;lt;/ControlTemplate&amp;gt;
    &amp;lt;/Setter.Value&amp;gt;
&amp;lt;/Setter&amp;gt;
</code></pre>

&lt;/Style&gt;

Lets look closely and what we have here. We have basically created a style that targets our user control. Our user control (as it inherits from UserControl) has a property called Template, which contains the layout logic itself. (Technically, the Template property lives on the Control object, which UserControl itself inherits from).

The Template property expects a control template, which we have given it. And inside the control template is simply the layout for our control. You see we have added a grid, the date picker and the combo box itself.

Notice that the bindings back to the CustomDateTimePicker file are a little different that usual. Instead we use either a TemplateBinding (rather than a standard Binding) or a standard binding with the relative source pointing back to the public property. TemplateBinding only works with dependency properties.

Consuming our custom control

To consume the user control, rather bind a value to it, start by adding a property to your view model (called SelectedDateTime) and give it a default value in the constructor;

public MainWindowViewModel()
{
    SelectedDateTime = DateTime.Now;
}

public DateTime SelectedDateTime { get; set; }

Now flip over to the xaml, and add the control;

<local:CustomDateTimePicker Grid.Column="1"
                            SelectedDateTime="{Binding SelectedDateTime, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Summary

There are many ways to create custom controls in WPF. We have seen one approach here where we create a code file that inherits from UserControl and and we define the layout for that control in a resource dictionary.

Download source code

I hope you enjoyed this mini series of introductory WPF MVVM tutorials.

WPF MVVM For WinForms Devs – Part 4/5

The purpose of this series of tutorials is to introduce the Model-View-ViewModel (MVVM) design pattern, and look at how to correctly implement it in an Windows Presentation Foundation (WPF) application. This series is targeted at developers of all levels, but especially at developers who are looking to make the transition from Windows Forms to WPF.

Events in Windows Forms applications

Assuming you have come from a Windows Forms background, regardless of what design patterns (if any?) you used, there is a good chance you are familiar with doing either or both of the following;

  • Double click a control (for example a button) to generate the event handler in the code behind;
private void button1_Click(object sender, EventArgs e)
{
}

or subscribe to the click event in the constructor, as follows;

public Form1()
{
    InitializeComponent();
    button1.Click += button1_Click;
}

private void button1_Click(object sender, EventArgs e)
{
}

Well, as you know code behind is not permitted in MVVM, so where do we go from here?  Well events pretty much don’t exist in MVVM.  This is quite a bold statement, but in reality you will very rarely need to subscribe to and unsubscribe from events in the “traditional” way.

This is somewhat of an over-generalisation because when you come to design user controls, you inevitably end up hooking into events as code behind is allowed in this scenario… and it can be “just easier” to subscribe to events.

Prism

We haven’t yet spoken about Prism, what it is and why you should care.  Prism (also known as the Microsoft Enterprise Library (Aka Patterns & Practices library)) provides lots of out of the box functionality to help make MVVM possible.  One feature is the Event Aggregator, which provides a mechanism for weakly subscribing to and unsubscribing from events in a safe way that avoids memory leaks.

Prism is out of the scope of this set of tutorials, but I recommend reading the MSDN documentation on how this works.

Commands

Commands are the WPF equivalent of reacting to user instigated interactions.  Commands are to WPF what Events are to WinForms.  Commands can be implemented in ways that make them reusable throughout your entire application, even across modules.

There are two approaches to create commands.  Firstly, you could create a new class and implement the ICommand interface.  The ICommand interface exposes the following;

  • CanExecute method (returns true if its OK to execute the actual command)
  • CanExecuteChanged event handler  (controls can and do subscribe to this to determine if the CanExecute value has changed)
  • Execute (called when the user actually wants to execute the command)
public class ClickCommand : ICommand
{
    #region ICommand Members
    public event EventHandler CanExecuteChanged;

<pre><code>public bool CanExecute(object parameter)
{
    return true;
}

public void Execute(object parameter)
{
    MessageBox.Show(&amp;quot;Clicked&amp;quot;);
}
#endregion
</code></pre>

}

This command will normally be used with UI elements by binding it to the Command property, which is available on many user input controls.

So that we can bind from our UI, add a property to your view-model of type ClickCommand;  (don’t forget to initialise the command in the constructor!)

public MainWindowViewModel()
{
    ClickCommand = new ClickCommand();
}

public ClickCommand ClickCommand { get; set; }

We can now bind this command to a control on our UI, in this case a Button;


<pre><code>&amp;lt;button Content=&amp;quot;Save&amp;quot;
        Command=&amp;quot;{Binding ClickCommand}&amp;quot; /&amp;gt;
</code></pre>

This is a good approach, but imagine this scenario;

You are creating a medium sized/large application that has lots of views/view-models.  You want to add a Save button to various views which, when clicked, persists some data to a database.  The actual data saved will vary between view-models.

Well a single ClickCommand isn’t going to help you here, because the code is too generic.


DelegateCommand and RelayCommand

DelegateCommand and RelayCommand are openly available, generic implementations of ICommand.  These implementations are not (yet!) implemented in the .NET framework… so fire up your favourite search engine and you should be able to find a wide variety of implementations for both.

Here is a simple version of DelegateCommand that I sometimes use. Notice that this example is not generic, meaning you have to cast from object to your target type. There are generic implementations widely available.

public class DelegateCommand : ICommand where T : class
{
    protected bool _isEnabled = true;
    private readonly Action _execute;
    private readonly Predicate _canExecute;

<pre><code>public event EventHandler CanExecuteChanged;

public DelegateCommand(Action execute, Predicate canExecute = null)
{
    _execute = execute;
    _canExecute = canExecute ?? (t =&amp;gt; _isEnabled);
}

public bool CanExecute(object parameter)
{
    return _canExecute((T)parameter);
}

public void Execute(object parameter)
{
    _execute((T)parameter);
}

public void RaiseCanExecuteChanged()
{
    var handler = CanExecuteChanged;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}
</code></pre>

}

Your view-model would look something like this;

public class MainWindowViewModel : BaseViewModel
{
    private string _myString;

<pre><code>public DelegateCommand&amp;lt;object&amp;gt; ClickCommand { get; set; }

public MainWindowViewModel()
{
    ClickCommand = new DelegateCommand&amp;lt;object&amp;gt;(OnClick, CanClick);
}

public string MyString
{
    get { return _myString; }
    set
    {
        _myString = value;
        OnPropertyChanged();
        ClickCommand.RaiseCanExecuteChanged();
    }
}

private void OnClick(object parameter)
{
    MessageBox.Show(&amp;quot;You clicked the button!&amp;quot;);
}

private bool CanClick(object parameter)
{
    return !string.IsNullOrEmpty(MyString);
}
</code></pre>

}

It becomes the responsibility of the view-model to decide what to do when the user clicks the button on your UI. To bind a button to the command, add a button as follows;

<Button Content="Click Me!"
        Command="{Binding ClickCommand}"/>

Summary

Unlike WinForms, there is not much of a concept of events in WPF. You could use the EventAggregator, which is part of the Enterprise Library from Microsoft, to subscribe to and unsubscribe from events in a weak way (a way that prevents memory leaks). Instead, we use commands, which enable use to write code that is highly reusable across our applications. Generic implementations of commands, such as DelegateCommand and RelayCommand, enable us to tailor code to specific view-models where appropriate.

WPF MVVM For WinForms Devs – Part 3/5

The purpose of this series of tutorials is to introduce the Model-View-ViewModel (MVVM) design pattern, and look at how to correctly implement it in a Windows Presentation Foundation (WPF) application. This series is targeted at developers of all levels, but especially at developers who are looking to make the transition from Windows Forms to WPF.

Capturing user input

In the previous walkthrough we; set up our view model, bound it to the view, and added a property for our model class.  We then displayed a customer name on the UI.

Let’s go ahead and make this slightly more interactive.  We want to expand our UI so that user can go ahead and update the customer details.

Update your code to the following;

&lt;Window x:Class=&quot;CustomerPortal.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local=&quot;clr-namespace:CustomerPortal&quot;
        Title=&quot;MainWindow&quot;
        Height=&quot;140&quot;
        Width=&quot;350&quot;&gt;
    &lt;Window.DataContext&gt;
        &lt;local:MainWindowViewModel /&gt;
    &lt;/Window.DataContext&gt;

<pre><code>&amp;lt;Grid Margin=&amp;quot;10&amp;quot;&amp;gt;
    &amp;lt;Grid.RowDefinitions&amp;gt;
        &amp;lt;RowDefinition Height=&amp;quot;Auto&amp;quot; /&amp;gt;
        &amp;lt;RowDefinition /&amp;gt;
        &amp;lt;RowDefinition /&amp;gt;
    &amp;lt;/Grid.RowDefinitions&amp;gt;
    &amp;lt;Grid.ColumnDefinitions&amp;gt;
        &amp;lt;ColumnDefinition /&amp;gt;
        &amp;lt;ColumnDefinition /&amp;gt;
    &amp;lt;/Grid.ColumnDefinitions&amp;gt;

    &amp;lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot;
                Grid.ColumnSpan=&amp;quot;2&amp;quot;
                VerticalAlignment=&amp;quot;Center&amp;quot;
                HorizontalAlignment=&amp;quot;Center&amp;quot;
                Margin=&amp;quot;10&amp;quot;&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;The customers name is:&amp;quot;
                   Margin=&amp;quot;0,0,5,0&amp;quot; /&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;{Binding Customer.LastName, Mode=OneWay}&amp;quot; /&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;,&amp;quot;
                   Margin=&amp;quot;0,0,5,0&amp;quot; /&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;{Binding Customer.FirstName, Mode=OneWay}&amp;quot; /&amp;gt;
    &amp;lt;/StackPanel&amp;gt;

    &amp;lt;TextBlock Text=&amp;quot;First Name:&amp;quot;
               Grid.Row=&amp;quot;1&amp;quot;/&amp;gt;

    &amp;lt;TextBox Text=&amp;quot;{Binding Customer.FirstName}&amp;quot;
             Grid.Row=&amp;quot;1&amp;quot;
             Grid.Column=&amp;quot;1&amp;quot; /&amp;gt;

    &amp;lt;TextBlock Text=&amp;quot;Last Name:&amp;quot;
               Grid.Row=&amp;quot;2&amp;quot; /&amp;gt;

    &amp;lt;TextBox Text=&amp;quot;{Binding Customer.LastName}&amp;quot;
             Grid.Row=&amp;quot;2&amp;quot;
             Grid.Column=&amp;quot;2&amp;quot; /&amp;gt;
&amp;lt;/Grid&amp;gt;
</code></pre>

&lt;/Window&gt;

The UI should now look something like this;

Updated UI

Let’s take a moment to review the behaviour…go ahead and make changes to the First Name and Last Name text boxes.  You will notice that when the text box loses focus, the Customers Name label is updated with the new values.  I can also assure you that the underlying model is also being updated to reflect these changes.

An unexpected situation

This works because the UI is instigating the update.  The user is making a change to a control which is bound to our model, and WPF knows to push this change to the model for us automatically.  So what happens when we instigate the change from our model class?  Take the following code;

protected override void AfterDelayElapsed()
{
    Customer.FirstName = "Bob";
    Customer.LastName = "Smith";
}

The above method (which is located in our MainWindowViewModel class) runs after a period of time (in this case 10 seconds) has elapsed.  Its reasonable to assume that because we have a TwoWay binding to the property on our view, the view should just be updated automatically.  This is not the case.

When making changes to your model classes, you have to inform the runtime that said property has changed.  This practice is known as raising change notifications in WPF. (and is arguably the vein of every WPF developers life).  There are several approaches you can take for raising change notifications, and they all start in the same way.

  • Your class must implement the INotifyPropertyChanged interface (System.ComponentModel.INotifyPropertyChanged).  This can be either on the individual class itself, or on a base class (the recommended approach)
  • The above interface provides an event that must be called, passing in the name of the property that has changed.

Base Classes Are Your Friend

I highly recommend that instead of implementing INotifyPropertyChanged directly on all of your model and view-model classes, you create a base class (called for example; BaseNotification or BaseViewModel or BaseModel) and implement the interface on there instead.  Then it is customary to have a protected method that actually takes care of raising the event.

First example implementation:

public class BaseNotification : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

<pre><code>protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code></pre>

}

Using this first approach, you will need to convert all your automatic properties on your model/view-model classes to properties with backing fields (full blown properties) and raise the OnPropertyChanged method passing in the name of the property.

For example;

public class Customer : BaseNotification
{
    private string _firstName;
    private string _lastName;

<pre><code>public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(&amp;quot;FirstName&amp;quot;);
    }
}

public string LastName
{
    get { return _lastName; }
    set
    {
        _lastName = value;
        OnPropertyChanged(&amp;quot;LastName&amp;quot;);
    }
}
</code></pre>

}

This approach is less than ideal because we effectively have magic strings in our code, and this is bad.  Not wrong, but bad.

If you are using the .NET Framework 4.5, you can easily eliminate the magic string by adding the CallerMemberName attribute to the the PropertyName parameter on your OnPropertyChanged method.

protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Note that the CallerMemberName attribute requires that the PropertyName parameter is an optional parameter.

So with this in mind, a property on our model class would now look like this;

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged();
    }
}

Don’t forget to add the using statement at the top of the file;

using System.Runtime.CompilerServices;

A Better Way

You’re in luck, there is one final way to resolve this nuisance…and we need to take a second to thank the open source community for this one.  Whilst there are several packages available, I am particularly fond of PropertyChanged.Fody … a free & open source project hosted on NuGet.

Package Manager Console

From a (very!) high level, this tool (and tools like it) convert your automatic properties into properties with backing fields and inject the OnPropertyChanged method call for you…all at compile time! (hold for applause)

So as long as your class either implements INotifyPropertyChanged directly, or gets it from a base model class, your work is done.


Summary

We can easily update the model from our view thanks to two way bindings, however when updating our model we need to notify the runtime that the property has changed…this is known as change notifications.  There are two main approaches to raising change notifications; implement INotifyPropertyChanged and raising the PropertyChanged event manually using a variety of techniques, or using a third party compile time tool to do this for us.

Next we will look at Events and Commands in WPF.

Revisions

Updated 26/6/13 – Altered description of CallerMemberName. Thanks Leom Burke!

WPF MVVM For WinForms Devs – Part 2/5

The purpose of this series of tutorials is to introduce the WPF MVVM (Model-View-ViewModel) design pattern, and look at how to correctly implement it in an Windows Presentation Foundation (WPF) application. This series is targeted at developers of all levels, but especially at developers who are looking to make the transition from Windows Forms to WPF.

How to quickly implement MVVM in your C# WPF application

Start by firing up an instance of your favourite version of Visual Studio (free or paid) and create a new WPF application, call it CustomerPortal.

VS Create Project Dialog

Add a new class to your project, called Customer.  This will be your model class.  Add the following code;

public class Customer
{
public int Id { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public DateTime DateOfBirth { get; set; }
}

Now create your view model class…remembering that the view-model is responsible for presenting the data within the model to the view.  Add the following code;

public class MainWindowViewModel
{
public MainWindowViewModel()
{
Customer = new Customer
{
DateOfBirth = DateTime.Parse("1970-01-01"),
FirstName = "Jon",
LastName = "Preece",
Id = 1
};
}

public Customer Customer { get; set; }

public string FullName
{
get
{
if (Customer == null)
return string.Empty;

return string.Format("{0}, {1}", Customer.LastName.ToUpper(), Customer.FirstName);
}
}
}

In this example, we are creating an instance of the model directly in the constructor (for simplicity). Typically this information would be retrieved from an external data source.

Finally, we need to let the view know about the view-model so that we can display the model data.  Edit the XAML in MainWindow.xaml so that it looks like this;

<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>

If you are unable to compile at this stage, check that the ‘local’ namespace (xmlns:local) matches the namespace your view-model class sits in.

For example:

xmlns:local="clr-namespace:CustomerPortal"

Finally, we’re ready to present the value of our FullName property to the user.  Replace the Grid in your view with the following code;

<StackPanel Margin="10"
Orientation="Horizontal">
<TextBlock Text="The customers name: " />
<TextBlock Text="{Binding FullName}" />
</StackPanel>

In the above sample, we have used data binding to retrieve the value of the property FullName from the views data context (our view model).

If you run the application, you should now see the following;

Main Window

Summary

We have seen how we can implement the MVVM design pattern in our application with very little effort.  We’ve seen the role played by the view-model.

We have not yet discussed how we get data back from the view to the model and the role of change notifications.  We will explore these topics and more in the next post.

Download  Download Source Code

  • 1
  • 2