Get in touch
Thank you
We will get back to you as soon as possible

9.11.2009

5 min read

WPF Apps With The Model-View-ViewModel Design Pattern

This article explains what MVVM design pattern is, and how to use it in WPF application software development. Here are also some words about WPF MVVM ToolKit. At the end you’ll see creating simple WPF MVVM application with data bind. I think all of us have tried to write some application on WPF and were absolutely excited about that technology (by the way, our company Binary Studio is leader on wpf outsourcing market). It looks good on not very big business application. What about really big ones? I suppose, some patterns could help to create a really big application and have good test covering, since XAML things have become a bit complicated in trying to conceptualize MVC architectures for Windows applications. The gap between web and win is narrowing and the whole WPF thing adds diverse possibilities to one’s toolbox. What to use? Model-view-controler, the model-view-presenter or the new paradigm called model-view-viewmodel?

WPF Model-View-ViewModel

In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler's Presentation Model, in that both patterns feature an abstraction of a View, which contains a View's state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In Glenn Block's excellent article "Prism: Patterns for Building Composite Applications with WPF" in the September 2008 issue, he explains the Microsoft Composite Application Guidance for WPF. But what is MVVM, and why is it useful?

 WPF Apps With The Model-View-ViewModel Design Pattern

  • DataModel is responsible for exposing data in a way that is easily consumable by WPF.
  • A ViewModel is a model for a view in the application (duh!). It exposes data relevant to the view and exposes the behaviors for the views, usually with Commands.
  • A View is the actual UI behind a view in the application. The pattern we use is to set the DataContext of a view to its ViewModel.
  • The ViewModel is the model of the view. That means: You want to DataBind a property from your DataObject (model) to a property from your ViewObject (view) but you sometimes cannot bind directly to a CLR property of the model (because of converting or calculating). This is when ViewModel comes into play. It propagates the already calculated or converted value from your model, so you can bind this property directly to the view property.

MVVM Data Binding Infrastructure

The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and entirely remove the need for writing code in a ViewModel that directly updates a view. The data binding system also supports input validation, which provides a standardized way of transmitting validation errors to a view. Two other features of WPF that make this pattern so usable are data templates and the resource system. In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free and fast regression testing, which helps reducing the cost of maintaining an application over time. As a result the development team can focus on creating robust ViewModel classes, and the design team can focus on making user-friendly Views. Connecting the output of both teams can involve little more than ensuring that the correct bindings exist in a view's XAML file. Also now using MVVM pattern is simpler because of WPF Model-View-ViewModel Toolkit 0.1. It creates all you need for MVVM in WPF. Just now I’m creating simple application with MVVM. Here is an overview of what the application does. It takes your first name, last name and age and displays it to you in a message box. Below is a really complicated class diagram. 

Class diagram

WPF PErsonModel Class

Let’s take a look at the PersonModel class which is the only Model in the application:

namespace MVVM.Model
{
internal class PersonModel : System.ComponentModel.INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged("LastName");
}
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChanged("Age");
}
}
#region INotifyPropertyChanged Members
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,
new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
#endregion
}
}

  Person class implements the INotifyPropertyChanged interface which enables a WPF element to be immediately notified if any of the properties changed on a Person object. Let’s look at the View which is cleverly named, PersonView:

<UserControl x:Class="MVVM.View.PersonView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="Auto" Width="Auto"
xmlns:local="clr-namespace:MVVM.ViewModel">
<StackPanel Orientation="Vertical" Margin="4">
<!--Here is where the view gets a reference to the ViewModel Declaratively-->
<StackPanel.DataContext>
<local:PersonViewModel />
</StackPanel.DataContext>
<StackPanel Orientation="Vertical" DataContext="{Binding Path=Person, Mode=TwoWay}"
Margin="4">
<StackPanel Orientation="Horizontal">
<Label Content="First Name:" Margin="0,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=FirstName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="Last Name:" Margin="0,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=LastName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="Age:" Margin="35,0,4,0"/>
<TextBox Width="50" MaxLength="3" Text="{Binding Path=Age}"/>
</StackPanel>
</StackPanel>
<StackPanel>
<!—The Command is bound to the Property in the PersonViewModel call SavePersonCommand-->
<Button Content="Save" HorizontalAlignment="Right" Width="80"
Command="{Binding Path=SavePersonCommand}"/>
</StackPanel>
</StackPanel>
</UserControl>

The key take away from the XAML above is the way the PersonViewModel is attached to the PersonView’s DataContext. (This is the typical means by which the View gets a reference to the ViewModel). Also pay attention to the Button element, whose Command is using the Binding class to attach the SavePersonCommand, which is a property on the ViewModel. Here is the entire PersonViewModel class:

namespace MVVM.ViewModel
{
internal class PersonViewModel
{
public PersonModel Person { get; set; }
private DelegateCommand savePersonCommand;
public ICommand SavePersonCommand
{
get
{
if(savePersonCommand == null)
savePersonCommand = new DelegateCommand(new Action(SaveExecuted),
new Func<bool>(SaveCanExecute));
return savePersonCommand;
}
}
public PersonViewModel()
{
//This data will load as the default person from the model attached to
//the view
Person = new PersonModel
{ FirstName = "John", LastName = "Doe", Age = 999 };
}
public bool SaveCanExecute()
{
return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) &&
!string.IsNullOrEmpty(Person.LastName);
}
public void SaveExecuted()
{
System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})",
Person.FirstName, Person.LastName, Person.Age));
}
}
}

WPF has a lot to offer for application developers, and learning to leverage that power requires a mindset shift. The Model-View-ViewModel pattern is a simple and effective set of guidelines for designing and implementing a WPF application. It allows you to create a strong separation between data, behavior, and presentation, making it easier to control the chaos that is software development. I’d like to recommend you only one reference about this technology and say thanks to John Gossman for his interesting blog about WPF. Artyom G., .NET team, Binary Studio

Thank you
We will get back to you as soon as possible

Looking for a tech partner to help you scale your project?

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Client Manager

0 Comments
name *
email *

Featured Case Studies