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 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 lets you record your weight and some notes on the Measurements screen:
This can be done for multiple users, which are set up on the Users screen:
(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).
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
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’.
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.
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:
- NUnit for unit testing
- RhinoMocks for isolation (mocking)
- Versant DB4O for the data store (it’s an Object Database, so don’t go looking for the SQL!)
- WPF Toolkit for the theme
- WPFMessageBox for the message box
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
Hopefully someone might find that useful. If you have any questions, feel free to get in touch.
A must-have tool for WPF development
Anyone who’s been working with WPF for any length of time will probably already know about this, but for anyone else, one of the tools you have to check out is Snoop, originally posted by Pete Blois and now hosted on CodePlex.
Snoop is basically a debugging aid which allows you to see exactly what’s happening in your running WPF app. This can be very handy, as XAML can get a bit confusing after more than a couple of buttons, and there are also problems like binding errors (when you miss-spell a property name in your XAML) not making themselves apparent.
Snoop runs against your running application, so if you do anything fancy with dynamic control generation, it will be included. One of the more useful aspects is the ability to see everything in the visual tree:
Aside from all of the properties of the selected control being shown, you might also notice the selected UserGrid being displayed, which is handy – Snoop also cleverly highlights the selected visual component on your running app:
You can also use this to show any controls which have binding errors (a common issue in WFP if ur spellin is bad like wat mine is):
As well as those genuinely useful features, there are a couple of really cool things which are good for showing off – the first is the ability to magnify your app (so you can prove WPF really is using vector graphics!):
Check out them corners.. Sweet!
And last but not least, watch in amazement as Snoop explodes your app into a magnificent 3D masterpiece!
And that’s not just a static image either, you can spin it around and all sorts. Now come on, who’s not going to be impressed by that?!
So, to summarise, Snoop for WPF – if you haven’t got it, go get it now!
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:
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..
(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…)