(WPFS) MVVM Light Toolkit: Soup To Nuts Part I

While I’m not a zealot on the topic, I do believe that MVVM offers one of the bestBreakthrough! patterns for Windows Phone development and so,   moving forward, the Windows Phone From Scratch series will incorporate MVVM in general, and the MVVM Light Toolkit in particular.

I’m more than convinced that MVVM is an essential pattern for Windows Phone Development; and while there are many excellent frameworks to make MVVM development easier, the one I personally prefer to work with is the MVVM Light Toolkit and so it is the one I’ll focus on.

I make the case for MVVM in this article, and so I won’t rehash that material here.   Instructions for installing MVVM Light Toolkit are available here

I will not assume any background with MVVM or with the Toolkit beyond those two links.  That is, I’ll assume you’ve loaded the toolkit and created your very first, single page MVVM application, but not more than that.

In that spirit, let’s begin by creating a two page MVVM application.  This immediately forces us to talk some issues I’ve not found in other introductory tutorials, and will, in the next tutorial bring up even more interesting topics, such as behaviors and messages(!)

Creating the Application

To begin,  open Visual Studio and click on New Project.  In Installed Templates select MVVMLight(WP7), and make sure that you see the option for MvvmLight (WP7). If not, please refer to the resources above to fix your installation.

Select MvvmLight and name the project MvvmLightNavigationBehaviorAndMessages. Run the application before touching the code, you’ll find that the application name and page name have been set for you and that there is a text block proclaiming “Welcome to MVVM Light” (!)  This is Laurent’s way of helping ensure that all is working well.

Linking the View and Its View-Model

Look in MainViewModel.cs and you’ll find three string properties: ApplicationTitle, PageName and WelcomeThese serve as properties to bind to on MainPage.xaml,

<StackPanel x:Name="TitlePanel"
            Grid.Row="0"
            Margin="24,24,0,12">
    <TextBlock x:Name="ApplicationTitle"
               Text="{Binding ApplicationTitle}"
               Style="{StaticResource PhoneTextNormalStyle}" />
    <TextBlock x:Name="PageTitle"
               Text="{Binding PageName}"
               Margin="-3,-8,0,0"
               Style="{StaticResource PhoneTextTitle1Style}" />
</StackPanel>

<Grid x:Name="ContentGrid"
      Grid.Row="1">

    <TextBlock Text="{Binding Welcome}"
               Style="{StaticResource PhoneTextNormalStyle}"
               HorizontalAlignment="Center"
               VerticalAlignment="Center"
               FontSize="40" />
</Grid>

All that is necessary is for MainPage to set MainViewModel to be its DataContext, which is accomplished on the 17th line of the file (at the end of the opening tag for the PhoneApplication page)

<phone:PhoneApplicationPage x:Class="MvvmLightNavigationBehaviorAndMessages.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            SupportedOrientations="Portrait"
                            Orientation="Portrait"
                            mc:Ignorable="d"
                            d:DesignWidth="480"
                            d:DesignHeight="768"
                            shell:SystemTray.IsVisible="True"
                            DataContext="{Binding Main, Source={StaticResource Locator}}">

Notice that this does not set the data context directly, but rather uses the StaticResource Locator

ViewModelLocator

It is worth diving into how this works, as the ViewModelLocator is central to the MVVM Light Toolkit.  This is one very good way, though not the only way, that you can set up the relationship between a view (MainPage) and its view model (MainViewModel) 

The static resource Locator is defined in App.xaml  

 <Application.Resources>
     <vm:ViewModelLocator x:Key="Locator"
                          d:IsDataSource="True" />
 </Application.Resources>

Finally, in the ViewModelLocator.cs file (created in the ViewModel folder when you created the application) you’ll find that the ViewModelLocator constructor calls CreateMain() which in turn sets the static property _main which is of type MainViewModel. 

The net effect is to link  (silently and without your intervention) MainPage to its view-model. 

When it is time to add a second page, as you’ll soon see, you have a bit of work to do, but it is all spelled out for you and there are code-snippets that make the work trivial.  Or nearly so.

Adding A Second Page

Let’s go most tutorials on MVVM Light one step further, and actually create that second page, and wire it up (I’m not sure that no other tutorial has done this yet, but I was hard-pressed to find one that did).

First, right-click on the project and create a new folder named Views.  Then  right click on Views and click on Add->New Item.  Select MVVM Page (WP7) and name the new page Page2.xaml. 

Hey! Page 2 is identical to MainPage.  That is because the bindings are the same and if you look closely you’ll see that it was “born” with the datacontext set to main.  Let’s fix that. 

Create a View-Model page for Page 2 named Page2ViewModel in the ViewModel folder (of type MvvmViewModel (WP7) ). 

Add the following public properties to the new View Model file:

 public string ApplicationTitle
 {
    get
    {
       return "MVVM LIGHT";
    }
 }

 public string PageName
 {
    get
    {
       return "Page 2";
    }
 }

 public string Welcome
 {
    get
    {
       return "Welcome to Page 2";
    }
 }

 

Now let’s connect them up.  Start by changing the name in the Datacontext in the view from Main to Page2ViewModel

Using the Code Snippets

Next, open the ViewModelLocator.cs file and scroll down to just below the constructor.  Here you can add most of the necessary code by using the mvvmlocatorproperty snippet.  Just type in the word and hit tab.  Overwrite with the name of the new type and the name of the local instance (in this case Page2ViewModel and _page2ViewModel.   Nearly all the code you need is created for you. Just add CreatePage2ViewModel() to the constructor.

Return to Page2.xaml and note that the page now reflects the new properties in the View Model. 

Next Step: Navigation with Behaviors and Messaging

What remains is to add a button on the first page that will cause a navigation to page 2.  This can certainly done in code-behind, but there is a better way: using behaviors and messages.  We’ll take that up in the next mini-tutorial.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Patterns & Skills. Bookmark the permalink.

32 Responses to (WPFS) MVVM Light Toolkit: Soup To Nuts Part I

Comments are closed.