Share via


Lab 10: Using the MVVM Pattern in Silverlight Applications

The Model-View-ViewModel (MVVM) pattern provides a flexible way to build Silverlight applications that promotes code re-use, simplifies maintenance and supports testing. The pattern consists of three different components including the Model (entities and code on the server), the View (the Silverlight screens) and the ViewModel (the glue between the Model and the View). An example of the how the Model, View and ViewModel components relate to each other is shown next:

Figure 1

The MVVM Pattern

In this lab exercise you'll learn how to migrate an existing Silverlight application that uses code-behind files for all of the C# or VB code into a more structured architecture that follows the MVVM pattern. Topics covered include creating a service agent class to handle calls to a WCF service, creating a ViewModelBase class, creating a custom ViewModel class and binding a ViewModel to a View declaratively in XAML. You'll also see how commanding can be used to wire-up events in a View to methods in a ViewModel. The application that you'll work with in the lab exercises is shown next:

Figure 2

Customer Details User Interface

Note:
It's recommended that you complete the data binding and WCF labs before starting this lab. Some of the steps in the lab will provide the code to use while others will explain the task to perform and let you figure out the code that should be added. If you need help with any of the steps refer to the lab's Completed folder which contains the finished code.

You Will Benefit from this Lab if

  • You're interested in building Silverlight applications that take advantage of code re-use, promote testability and reduce maintenance costs
  • You'd like to separate your Silverlight application into distinct modules and provide a pattern that can be followed by a team of developers
  • You're interested in learning the MVVM pattern and the benefits it offers

You Will Learn:

  • How to convert an existing Silverlight application to use the MVVM pattern
  • The role of the Model, ViewModel and View in the MVVM pattern
  • How to create a service agent class and the role it can play in an application to promote code re-use
  • How to create a ViewModel class and handle property change notifications
  • How to bind a ViewModel class to a View
  • How to communicate between a View and ViewModel using commanding

Business Requirements for the Silverlight application include:

  • Remove existing code from a Silverlight code-beside file
  • Create a service agent interface and class to handle calls to a WCF service
  • Create a ViewModelBase class to handle INotifyPropertyChanged notifications
  • Create a ViewModel class that derives from ViewModelBase and handles data interactions
  • Add support for commanding into a ViewModel class
  • Bind a ViewModel class to a View in XAML
  • Bind Silverlight controls to ViewModel properties

Estimated Time: 45 minutes