Written by: Jeremiah Morrill



MVVM has been a trending topic lately. And why shouldn’t it be? People want to build great WPF/SL applications and want guidance on how to build them using the framework’s strengths. If you are anything like me, you started your WPF/SL career, learning the framework classes and hierarchy. You learned XAML, triggers, storyboards and animations. You even hobbled together something that looked mind blowing, but the code was a monstrosity. Where do you go from here? How do you leverage all this separation of UI and biz-code that was promised in WPF?

I’m going to go out on a limb and make a wild assumption. I believe the majority of people that are trying to learn MVVM [and are having trouble] have never practiced any sort of UI application pattern. Maybe they dabbled in MVC/MVP. Maybe they studied the GoF patterns in school. Why do I assume this? Well because that describes myself and it describes lots of other developers I’ve interacted with. Not very scientific reasoning, but I’m going with it anyways. Because of this lack of general experience, MVVM tutorials and write-ups can be difficult for many developers. Some of these developers will no doubt take MVVM as a very strict pattern and do not deviate from what their perception of MVVM purity is as not to upset the MVVM gods. So that said, the rest of this write up I’m going to try to start from square one. As if I was talking to myself years ago. Layman as #%$@.

Beginner’s MVVM Challenge #1 |or| Takin’ You Down to MVVM Town

So we want to begin our journey into MVVM town by way of Bindingopolis. Our first web search brings us to a tutorial talking a bunch of mumbo jumbo about models, views and view-models. Usually you get a good description of what each is in concept, which is cool, but we also want to know what is it in CODE?

A model is a class that has your data. No magic here.

class Model { public string Name { get; set; } public string Address { get; set; } }

A view is, for the sake of explanation, is a UserControl. It’s a kind of like a mullet. Except its a party in the front, code in the back.

/// /// Interaction logic for View.xaml /// public partial class View : UserControl { public View() { InitializeComponent(); } }

A View-Model is, again, just another class. This is where your View (aka UserControl) will get it’s data. It’s a data abstraction of your View. So if you view needs some data, this is where it gets it. If values need to be converted/formatted, this would be a good place to do it. Take special notice of the INotifyPropertyChanged interface.

class ViewModel : INotifyPropertyChanged { private Model m_model; public ViewModel() { m_model = new Model(); } public string Name { get { return m_model.Name; } set { if (m_model.Name != value ) { m_model.Name = value ; InvokePropertyChanged( "Name" ); } } } public event PropertyChangedEventHandler PropertyChanged; private void InvokePropertyChanged( string propertyName) { var e = new PropertyChangedEventArgs(propertyName); PropertyChangedEventHandler changed = PropertyChanged; if (changed != null ) changed( this , e); } }

The ViewModel class is really up to you how you want to design it. The INotifyPropertyChanged interface allows us to update bindings (more later). It’s accepted practice to make a base class for the ViewModel. Some folks inherit from DependencyObject and make dependency properties for things in their view model. Don’t do this . Those people are sadists.

Beginner’s MVVM Challenge #2 |or| A Menage a Trois That Won’t Get You in Trouble

So how do our three players, the Model, View and ViewModel, work together? What sort of witchcraft must we implement? DataContext (again, for the sake of simplicity). Take a look at your View’s (UserControl) class hierarchy. You’ll see FrameworkElement in there. This has a property called DataContext of type object. When you set the DataContext, it will propagate down the tree. So to answer the question of how these all fit…Your model is loaded from where-ever, a data base, a file, etc. Your ViewModel gets your Model and exposes it’s data to your View. Your View gets access to your ViewModel from, wait for it…the DataContext.

Consider this from our code snippets above:

myView.DataContext = new ViewModel();

And the XAML for the “View” class.

< UserControl x:Class ="WpfApplication3.View" xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" Height ="300" Width ="300" > < Grid > < TextBlock Text ="{Binding Name}" /> Grid > UserControl >

So you see, we explicitly set the DataContext. We also setup a binding in our View’s XAML. WPF/SL will automatically look at the DataContext via reflection and pull out value for the “Name” property. If we write code in our ViewModel to change the value of the “Name” property, it will automatically be updated in our UI via the binding. This is the purpose for INotifyPropertyChanged.

If we want to update the value in the view model from the UI we’d do something like this:

< TextBox Text ="{Binding Name, Mode=TwoWay}" />

Now when we run this, the the value of the “Name” property will be in a TextBox. When you edit the value (and the TextBox loses focus), the view model’s Name property will be updated.

I would like to mention that getting the View and ViewModel together is a topic in itself. Some people explicitly set the ViewModel to the DataContext. Some people set it in the XAML. Some people just include the ViewModel as a and do StaticResource bindings to it. Some people use dependency injection and some use a service locator pattern (or both DI and ServiceLocator). All of these have it’s pro’s and cons. It all depends what is important to you.

So now all this raises another question: Why even bother? I can just load my model from code-behind and fill in the properties myself.

We have successfully partitioned our application. A designer can edit the Views XAML in Blend without too much fear of breaking any business logic. They can design without Blend crashing on them. Your code now has a separation of concerns, making extensibility, testing and maintenance much less involved than stepping through thousands of lines of interconnected, circular dependant spaghetti. Don’t get me wrong, you can still write shit code in MVVM, but MVVM is a good start in avoiding shit code.

Beginner’s MVVM Challenge #3 |or| MVVM is a Mole-hill, Not a Mountain.

In my opinion, the last couple pages, this is all MVVM is. It’s NOTHING more.

“But Jer”, you say, “How do I make my View do X with the ViewModel? How do I make my ViewModel do Y to the View? This can’t be IT. There’s gotta be more to MVVM.” Yes there is more, but not to MVVM. There are other patterns you should be aware of to assist you in MVVM. Patterns like commanding (baked into WPF, solutions for SL), mediator and *gasp* dependency injection. There’s other facilities baked into WPF and Silverlight that can further assist, such as the ItemsControl and data templates. I will, in a later post, talk more deeply on these subjects in an article named “Anatomy of an MVVM Application *or* How Tards Like Me Make MVVM Apps”.