Archive

Posts Tagged ‘Patterns’

WPF MVVM Example App

June 8, 2010 14 comments

I’ve been writing a simple app to try out Windows Presentation Foundation (WPF) using the Model-View-ViewModel (MVVM) pattern, so I thought I’d post it in case anyone found it useful – there don’t seem to be many end-to-end examples using MVVM around.  I’ve tried to stick to good practices, although there’s still a fair bit of discussion in some areas about what the best way to do things is.

Before you read any further, if you’re looking for an example of a decent WPF UI, stop now!  I can assure you, you’ll only be disappointed..  I used a theme so it wasn’t grey, but that’s about it.  It’s all about the code!

The Code

The source code is here: https://github.com/relentless/wpf-diet-recorder

You’ll need Visual Studio 2008 and above to use this (I haven’t tried it with 2010, but it should work Ok).

The App

The app lets you record your weight and some notes on the Measurements screen:

measurements screenshot

This can be done for multiple users, which are set up on the Users screen:

users screenshot

(You might notice the Users screen allows you to define custom measurements for the users – these aren’t used anywhere at the moment, as putting that in was making it too complex for this example).

Features

A couple of interesting things in there are:

  • Automated Unit Testing (of course!)
  • Composite views (the ‘custom measurements’ part of the Users screen is a separate user control with its own ViewModel)
  • No code-behind
  • Commands using DelegateCommand
  • ValueConverters

Unit Testing

Although there aren’t as many unit tests as I would like, there should be at least examples of the main things you’d want to test.  (My only excuse for the lack of tests is this was my first WPF app, and as such basically a prototype, so I was working it out as I went along).

I’ve used Roy Osherove’s naming convention for the unit tests (MethodName_StateUnderTest_ExpectedBehaviour), as I like it.  I’ve also stuck with the AAA pattern for the test layout (Arrange, Act, Assert), and when I’ve used Rhino Mocks for test isolation, that’s been in ‘AAA mode’.

ValueConverters

There is still much discussion in MVVM circles about whether ValueConverters should be used, or if the ViewModel in MVVM should render them unnecessary.  I’ve used ValueConverters as I don’t want to have too View-specific things (such as Visibilities and Colours) in my ViewModel, but some people (including Josh Smith, the father of MVVM) disagree.  To be honest, it doesn’t matter much (especially if you’re just starting out), but it’s good to be aware of your options.

Validation

Always tricky to know where to put the validation – in this case, I’ve gone for validating the data type in the ViewModel, and any more complex validation (string lengths, max and min value, etc) in the model itself.

Libraries / Tools

The things I’ve used to build this (aside from VS2008) are:

Further Development

If I was to continue developing this example, there are a couple of things I’d probably want to do:

  • Make some kind of Application Controller, which would contain the ugly startup code from App.xaml.cs and be in charge of opening forms
  • Use an IoC container such an Ninject to resolve those dependencies
  • Probably take the data loading/saving logic out of the ViewModels and find somewhere more appropriate for it

That’s It!

Hopefully someone might find that useful.  If you have any questions, feel free to get in touch.

Advertisements
Categories: WPF Tags: , ,

Simplified MVVM Commanding with DelegateCommand

March 30, 2010 13 comments

The MVVM (Model-Miew-ViewModel) pattern for WPF works really well, but for me has one big disadvantage – the sheer verbosity of it.  There’s just so much code to type!  Especially when you’re going for the ‘pure’ approach of no code in your code-behind.

One of the worst offenders for this is the Command model, whereby in your ViewModel you define a class which implements ICommand.  This is made available to the View via a property, and when called, calls some method in your ViewModel.

(Note:  This only applies to WPF.  Silverlight doesn’t currently support commands in the same way.)

Here’s an example, from inside my ViewModel (MeasurementViewModel):

(This is set up in the XAML as follows:)

You can see the custom ICommand (AddDefinitionCommand), a local variable to hold it, and a property getter for the view to find it.  Now considering that this doesn’t even have the code which performs the action (which is viewModel.AddMeasurementDefinition), that’s lot of overhead.  And you have to do that for every single command!  That’s button clicks, selection changes, and so on.

One of the problems is that the Command model provides a lot of flexibility by defining the CanExecute() method and CanExecuteChanged event, but I don’t need those in my simple scenario.

So, how to write a bit less code?  Of course, you could make some good use of Code Snippets, but there are better solutions.  The best one I’ve found is the DelegateCommand approach used in Microsoft’s Composite Application Library (a.k.a Prism), also discussed in Josh Smith’s MVVM article (where he calls it a RelayCommand).  This involves defining an ICommand which uses delegates, and means you have less boilerplate code to write.

As I’m not interested in using the full features of the ICommand, my simple DelegateCommand goes like this:

DelegateCommand class definition

DelegateCommand.cs

And to call it, you simply need the following:

You can see the local member for the DelegateCommand, the ViewModel constructor where we define the method to call, and the property to make it available to the View.  Much simpler, I’m sure you’ll agree!

Of course, if you want to include the rest of the Command functionality, you can just extend the DelegateCommand.  So there you have it, all of your MVVM problems solved!  Well, nearly..

The Code

(As I don’t seem to be able to upload DelegateCommand.cs for you to download, here’s the text for you to copy & paste.  I’ll work WordPress out one of these days…)

using System;
using System.Windows.Input;
namespace CommandUtils
{
public class DelegateCommand: ICommand
{
private Action _executeMethod;
public DelegateCommand(Action executeMethod)
{
_executeMethod = executeMethod;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_executeMethod.Invoke();
}
}
}
Edit: To see this in action, check out my MVVM Example App
Categories: WPF Tags: , ,