Tuesday, March 01, 2011

Getting Started with the MVVM Pattern in Silverlight Applications

With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be downloaded here.

Getting Started with the MVVM Pattern

The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course we offer that sums up the role of each part of the MVVM pattern in a concise way:

clip_image002_thumb_62E31C00.jpg

Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.
The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View's responsibilities include displaying data and collecting data from end users. A given View isn't responsible for retrieving data, performing any business rules or validating data.

The ViewModel acts as the middle-man between the View and the Model. It's responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List<State> property and a List<Person> property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn't have to worry about retrieving data and knows nothing about where data comes from.

Read more: Dan Wahlin's WebLog