The construction of a ViewModel is often seen as the standard technique for solving binding problems within WPF and Silverlight. However, the addition of a ViewModel adds complexity to your code. This post describes an alternative method where a mini-ViewModel is applied directly to the problem areas in the view, leaving the rest to use simpler, straightforward binding to business objects.
One of the features of WPF / Silverlight that appealed to me immediately when I started to learn it was the flexibility of the binding framework. The concepts of DataContext inheritence and flexibility of the value converters results in a lot less glue-code, which makes me a happy developer! However, it does not take long before you start finding examples that just dont fit with the framework and things start to get just little more complex. This blog post describes one such example.
The example used in this blog post is of a very simple application which displays a business card. The business object rendered by the application, ContactDetails, has a number of simple CLR properties. Constructing a UI for viewing this business object is very easy, simply create an instance of this object (in a real application this object might come from a database or web service) and set it as the DataContext of the view:
public Page() { InitializeComponent(); ContactDetails details = new ContactDetails() { Company = "Scott Logic Ltd.", Email = "ceberhardt@scottlogic.co.uk", URL = "http://www.scottlogic.co.uk", Country = "UK", FullName = "Colin Eberhardt", PhoneNumber = 4408452241930 }; this.DataContext = details; }
We then create some simple XAML with UI elements that bind to the various propeties of our object …
<Grid x:Name="LayoutRoot" Background="White"> <Border BorderBrush="LightGray" Background="White" BorderThickness="1.5" CornerRadius="20" VerticalAlignment="Center" HorizontalAlignment="Center"> <Border Margin="5" BorderBrush="LightGray" BorderThickness="1.5" CornerRadius="15"> <Border.Background> <ImageBrush> <ImageBrush.ImageSource> <BitmapImage UriSource="back.jpg" /> </ImageBrush.ImageSource> </ImageBrush> </Border.Background> <StackPanel Orientation="Vertical" Margin="10"> <TextBlock Text="{Binding FullName}" FontSize="15" FontWeight="Bold" /> <Rectangle Stroke="DarkGray" HorizontalAlignment="Stretch" StrokeThickness="0.5" Height="1"/> <TextBlock Text="{Binding Company}" Margin="0,10,0,0"/> <StackPanel Orientation="Horizontal" > <TextBlock Text="e: "/> <TextBlock Text="{Binding Email}" /> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="w: "/> <HyperlinkButton Content="{Binding URL}"/> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="p: "/> <TextBlock Text="{Binding PhoneNumber}"/> </StackPanel> </StackPanel> </Border> </Border> </Grid>
And we get a lovely looking business card:

One problem with the above example is the phone number, outputting the raw number ‘4408452241930′ is not terribly readable, besides phone numbers have a standard format, in this case, the phone number would be represented as ‘+44 (0)845 2241930′. Also, let’s make the problem more interesting; you might want to highlight the international dialing code in a different colour, or, if the application is being used by a UK client, display the number in a local format without the international code ‘0845 2241930′. So just how do we achieve this?
In order to break the number up into different blocks of text, with different colours (i.e. styles), we need to modify our view to have multiple TextBlocks mapped to the PhoneNumber property of our business object. The part of our view which renders the phone number is modified as follows:
<StackPanel Orientation="Horizontal"> <TextBlock Text="p: "/> <TextBlock Text="... country code ..." Foreground="LightGray"/> <TextBlock Text="... area code ..."/> <TextBlock Text="... local number ..."/> </StackPanel>
But just how exactly do we bind the properties of these business objects?
One approach would be to use a value converter for each binding in order to extract the required part of the number, for example a CountryCodeValueConverter could be implemented which grabs the first 2 digits of the number. However, this approach is a little inelligent in that it fragments our logic into a number of separate classes, furthermore, if we want country specific formatting this requires the use of multibindings, which can be rather cumbersome if over-used (for a Silverlight implementation of multi bindings see my blog post from earlier this year).
Another approach which is often used to tackle tricky binding problems is the use of the Model-View-ViewModel (MVVM) pattern. With this pattern, our ContactDetails object is the Model, we construct a ViewModel which is a UI-oriented abstraction of the Model and it is this which we bind to the View. WPF guru Josh Smith describes MVVM as “a value converter on steroids” in order to highlight the usefulness of the pattern in this context.
The basic approach used here is to bind your View to a ViewModel rather than binding it to the business object directly. The ViewModel is specific to the view and wraps the business object (i.e. Model), forwarding the property values and change notification to the View. This extra layer allows us to supplement the properties of the Model object, adding new computed properties which are specific to the View. In this case, these computed properties can be used to expose ‘country code’, ‘area code’, etc… to our View.
(This is a common pattern so I am not going to reproduce the code required here, however, if you are interested, the attached sourcecode accompanying this article contains a regular ViewModel version as well as a mini-ViewModel implementation)
Whilst this approach works, my issue with it is that it adds quite a bit of boiler-plate code for wrapping properties, forwarding events etc … The removal of this glue-code is the exact reason that I like WPF/Silverlight so much! The MVVM pattern is primarily for supporting the designer-developer paradigm and enabling unit testing of UI applications, in my opinion the use of MVVM for anything else is just plain wrong!
So, how can we solve the problem of providing a nicely formatted phone number without the pain of bashing out line-after-line line of boiler-plate MVVM code? My solution to the problem isn’t to dispose of the MVVM pattern altogether, rather, it is to localise its usage to just the problem area. The first step is to encapsulate the rendering of the phone number as a user control:
... <StackPanel Orientation="Horizontal"> <TextBlock Text="p: "/> <local:PhoneNumberControl Number="{Binding PhoneNumber}" /> </StackPanel> ...
… which probably makes sense anyway from a perspective of good design and code re-use!
Now that we have moved the phone number property within the PhoneNumberControl we have isolated the problem and can deal with it locally. We can create a PhoneNumberControlViewModel which splits the phone number up into its various components and bind this to the PhoneNumberControl.
The control’s ViewModel looks something like this:
public class PhoneNumberControlViewModel : INotifyPropertyChanged { public PhoneNumberControlViewModel(PhoneNumberControl ctrl) { _ctrl = ctrl; ComputeProperties(); // listen to property changes in the control (we are interested // in just the Number property) _ctrl.PropertyChanged += Control_PropertyChanged; } private PhoneNumberControl _ctrl; private string _countryCodeText; private string _areaCodeText; private string _localNumberText; public string CountryCodeText { get { return _countryCodeText; } set { _countryCodeText = value; OnPropertyChanged("CountryCodeText"); } } public string AreaCodeText { get { return _areaCodeText; } set { _areaCodeText = value; OnPropertyChanged("AreaCodeText"); } } public string LocalNumberText { get { return _localNumberText; } set { _localNumberText = value; OnPropertyChanged("LocalNumberText"); } } private void Control_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Number" || e.PropertyName == "Country") { ComputeProperties(); } } private void ComputeProperties() { string formattedNumber = _ctrl.Number.ToString(); CountryCodeText = "+" + formattedNumber.Substring(0, 2); AreaCodeText = " (" + formattedNumber.Substring(2, 1) + ")" + formattedNumber.Substring(3, 3); LocalNumberText = " " + formattedNumber.Substring(6); } }
Note that here the ViewModel is ‘wrapping’ the PhoneNumberControl rather than an instance of some Business / Model object.
Now we just set our ViewModel as the DataContext for the View, as per the typical usage of this pattern:
public PhoneNumberControl() { InitializeComponent(); this.DataContext = new PhoneNumberControlViewModel(this); }
… and it doesn’t work. If you try the above, you will find that the binding on the PhoneNumberControls Number property no longer works. So why is this? if you look back at where the PhoneNumberControl instance is defined in our business card’s XAML markup you see that its Number property is bound as follows:
<local:PhoneNumberControl Number="{Binding PhoneNumber}" />The source of this binding is not explicitly set, so will default to using the DataContext of the PhoneNumberControl instance. However, we have just changed this DataContext in our constructor to something else … oops!
Solving this problem is actually quite simple, the PhoneNumberControl markup is as follows:
<UserControl x:Class="SLMiniViewModel.PhoneNumberControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel x:Name="LayoutRoot" Orientation="Horizontal"> <TextBlock Text="{Binding CountryCodeText}" Foreground="DarkGray"/> <TextBlock Text="{Binding AreaCodeText}"/> <TextBlock Text="{Binding LocalNumberText}"/> </StackPanel> </UserControl>
If we modify our binding to the ViewModel as follows:
public PhoneNumberControl() { InitializeComponent(); LayoutRoot.DataContext = new PhoneNumberControlViewModel(this); }
The subtle difference being that the ViewModel is now bound to the StackPanel which is the root of our visual tree within the control. This means that the PhoneNumberControl DataContext is still inherited from the business card and is our business object instance, the DataContext switch to the ViewModel is now neatly tucked just within the PhoneNumberControls visual tree, and it is this DataContext which our TextBlocks will inherit and bind to.
The result is that we can now use our mini-ViewModel embedded within the PhoneNumberControl to expose properties which are more amenable to binding to our View:

Whilst this is a quite trivial example, in real-world applications, more complex examples where the data representation within the View is dependant on a number of properties are quite common. The source code accompanying this article extends the example a little further by making the formatting dependant on a second property of the business object. This is the sort of problem that would either push you towards multi-binding and numerous fragmented value converters, or a ViewModel.
In conclusion, the use of a mini-ViewModel which is embedded within a UserControl allows you to solve tricky binding problems without being weighed down by rolling out the MVVM pattern across your entire View. I am not against the MVVM pattern in itself, however I do firmly believe that it should only be used to solve the problems which it is was specifically designed for, i.e. supporting the designer-developer workflow and unit testing.
You can download the source-code for this article: SLMiniViewModel.zip – this project contains both MVVM and mini-MVVM implementations (count the number of lines in the ViewModel and contrast it with the mini-ViewModel).
Regards, Colin E.
Tags: binding, mvvm, silverlight, WPF




Another Excellent write up, I will be sure to save this in my Reddit account. Have a great evening.
Hi Matt,
Glad you found this article interesting. I have also found myself transferring WPF patterns to WinForms, as you know we use MVVM for our grid controls. (However, MVVM is really just a new and sexy name for the Martin Fowler’s presentation-model pattern!)
Regarding unit testing, I had this same discussion with Gergely yesterday, I don’t believe in unit testing UI code.
With the example I use in this blog post, the ViewModel is being used as a means to format a phone number, something that is hard to achieve with the tools available in the WPF framework. The important point to me is that this is ‘formatting’, i.e. pure presentation.
Sure, you could try and unit test it, however, what if someone screws up the positioning of the controls, or the font? your tests would pass, but the UI would be all wrong! In my opinion UIs should be tested by humans.
(Having said that, I probably would unit test the parts of the code which manipulate the phone number and extract its component parts – however, I would make this a separate, non UI-centric unit!)
Regards, Colin E.
Oops: “is something I’ll add TO MY toolbox.”
Interesting article Colin!
I tried applying this pattern directly to WinForms (given the projects I work with currently are WinForms) and it comes up quite nicely.
I do share Brian Genisio’s concern about unit testing, but its an interesting point about not coupling the View and ViewModel to any business objects – "decompose it into a number of re-usable controls, each containing mini-ViewModels". I guess you could introduce an interface for business objects to use, but that adds complexity and defeats the purpose of your article.
Think miniViewModel is something I’ll add toolbox. Thanks Colin.
Hi Tim,
Thanks for your feedback. Personally I think the problem (if it is indeed a problem!) is that WPF (and Silverlight) is in itself both a powerful and complex framework. You really need to learn how it works, and DataContext inheritance is part of this learning process.
Regards, Colin E.
Btw, the additional “black magic” to which I was referring was the multiple data contexts for a single control – that inherited by the control itself, and that specified by the control on its LayoutRoot. James’ confusion being a case in point.
Thanks for this – I’d thought of a similar solution, and it’s nice to be validated
However, I’m hesitant to do this type of thing simply because of the additional layer of “black magic” it introduces. I mean, I understand what’s going on, and I’m wary of the debugging spectre this introduces – I have a really hard time foisting this onto whoever is left to follow in my footsteps down the line. That said – I may well do it anyway, as the alternatives are perhaps much less pretty. I’m thinking about imperative binding for this, though – remove the binding code from the xaml to the code, just so it’s at least visible and available to refactoring tools, etc.
Hi,
I found this article very inspiring and awarded you 5 Sticky Stars…
Thanks Hans .. those stars are yummy
[...] Eberhardt describes the Mini-ViewModel pattern here and gives a nice [...]
Colin:
Your final flourish: “LayoutRoot.DataContext = …” was what brought to an end an afternoon of hair-removal. As a relative newcomer to WPF, I would never have guessed that such a setting would be required to get my not-dissimilar app working. A thousand Thank Yous!
Could you possibly direct me to more information on this exact topic? – that might describe why “this.DataContext=…” does not work, or possibly give other ways to acheive the same end – I am about to look up the RelativeSource binding setting in case it is related. The relevance of the “ElementName” setting is also a mystery at present.
Regards
James.
@James,
ElementName is just one technique which you can use to locate the source of a binding. It is most often used when connecting together a couple of UI elements.
Colin E.
Colin,
First off, I want to say that I mean no disrespect by questioning you. I hope I don’t come off as antagonistic… that is not my intent here.
That being said, I still see this approach as being an obstacle to unit testing. I use NUnit to unit-test my Silverlight code. Within NUnit, there is no way to instantiate anything that derives from DependencyObject under test. The Silverlight runtime is not initialized, which is fine by me since I am writing unit tests. Because the MiniViewModel relies on a UserControl, the ViewModel cannot be tested in that environment.
It seems to me that if your PhoneNumberControlViewModel depends on ContactDetails instead, you wouldn’t have any more code than if it depends on PhoneNumberControl.
I create small ViewModels for small views all the time that are simple wrappers around model objects… very much like this case. The ViewModels only expose the properties that the View relies on, and I don’t find there to be more code than what you are proposing here.
I might be missing something here. I guess I am not clear to what problem the MiniViewModel solves. Is it possible to post the ViewModel implementation to compare it to the MiniViewModel?
Hi Brian,
(Would have replied sooner – busy finishing off my kitchen re-fit!)
Antagonistic? not at all. There is nothing better than having someone provide well thought-out feedback for an article.
I would not wish to make PhoneNumberControlViewModel depend on ContactDetails because it is a component part of PhoneNumberControl, a control which would probably be developed into a generic component for displaying phone numbers as the application development evolves. Therefore, I do not see it as being tightly coupled to the example application.
Yes, I agree, having PhoneNumberControlViewModel tightly coupled to the view is an obstacle to unit testing. But, do you know what? I don’t think I would unit test the PhoneNumberControl! (shock! horror!) … I believe in pragmatic unit testing, where your unit test important or complex functionality, but don’t test the more trivial stuff.
You ask about posting the ViewModel implementation, just download and unzip the solution associated with the article, it contains both. You will see that the PhoneNumberControlViewModel is quite a bit smaller that the ContactDetailsViewModel and lacks all the boiler-plate property and change notification forwarding. Whilst this is only a simple example, I have used it in practice for more complex views, where I have been able to decompose it into a number of re-usable controls, each containing mini-ViewModels, allowing me to bind my business object directly to the view.
Thanks for the feedback.
Regards,
Colin E.
Colin,
I am a little confused here. Your PhoneNumberControlViewModel relies directly on your View control (PhoneNumberControl). This makes testing more difficult due to the tight coupling to the UI layer.
Why not have PhoneNumberControlViewModel wrap ContactDetails, instead?
Hi Brian,
Let me see if I can explain … My motiviation here was to demonstrate how a tricky binding problem can be solved without a full-scale ViewModel, resulting in direct business object to View binding and simpler code. There are often times when you do not need/want to unit test (or have a seperate designer-developer workflow), and in these cases simplicity is a real boost to productivity.
Whilst I agree, PhoneNumberControlViewModel is tightly bound to the View, by virtue o fthe fact that it hold a refence to it, I do not see this as an obstacle to unit testing. The PhoneNumberControl is a purely visual component, i.e. it has not embedded logic which affects the bound business object, therefore, there is no value in decoupling its ViewModel from the View. If within this application, you did add some significant logic, and wished to unit test it, it would be possible to insert a view model between ContactDetails and the view. This ContactDetailsViewModel would be the decoupling you need in order to unit test.
I hope this makes sense!
Colin E.
The mini-ViewModel pattern – Colin Eberhardt’s Adventures in WPF…
Thank you for submitting this cool story – Trackback from DotNetShoutout…