Windows Phone From Scratch #19 – MVVM Light Toolkit Soup To Nuts #4

Let’s back up a bit and examine the day to day use of a View Model, and binding to the Glue Kid view model.  In this mini-tutorial I’ll show the basics of binding a collection that sits in a View Model to a list box in the view.  In the next, I’ll show how to capture the selection and, in the view model, determine what the details page should show.

Let’s create a simple application that will display the full name of customers and their email, and that will (eventually) allow the user to click on one and go to the details about that customer.

We start by creating a new MVVM application for Windows Phone.  Once created, open the application in Expression Blend and add a ListBox to the content panel. I chose to have it fill the entire panel with a small margin all around. 

Creating the CustomerCollection

The CustomerCollection class exists to give us some data to work with.  I “borrowed” this class from a previous demo and have included it with the source code.  We can summarize it here by saying that the class consists of a number of fields ( First, Last, Address, City, Zip, Phone, Fax, Email) , properties and most important a property Customers that returns an observable collection of Customer instances generated by mixing and matching values for the fields randomly.

Binding the ItemSource

The key to understanding how MVVM handles the data binding is that the DataContext for the View is the View Model.  The binding for the ItemsSource is created as you might expect, in the view:

<ListBox
   x:Name="PersonListBox"
   Margin="10"
   ItemsSource="{Binding Customers}">

 

When you set up the MVVM Light application the data context for this page was set to the view model, and there you’ll need a (read only) property for binding. I suggest using the code snippet that was installed with the MVVM Light Toolkit.

Thus, back in Visual Studio, in the code behind file, MainViewModel.cs, enter the letters mvvminpc and press tab.  This will expand to a property, and by using tab you can set the property name to Customers and the backing variable to _customers.  It turns out that we won’t need either the backing variable nor the setter, as we’ll use the Customers property from the CustomerCollection class.

public ObservableCollection<Customer> Customers
{
   get
   {
      var customerCollection = new CustomerCollection();
      return customerCollection.Customers;
   }
}

 

All that is left is to provide a DataTemplate in the view so that each Customer is displayed as we wish,

<ListBox
   x:Name="PersonListBox"
   Margin="10"
   ItemsSource="{Binding Customers}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel>
            <StackPanel
               x:Name="DataTemplateStackPanel"
               Orientation="Horizontal">
               <TextBlock
                  x:Name="FirstName"
                  Text="{Binding First}"
                  Margin="0,0,5,0"
                  Style="{StaticResource PhoneTextExtraLargeStyle}" />
               <TextBlock
                  x:Name="LastName"
                  Text="{Binding Last}"
                  Margin="0"
                  Style="{StaticResource PhoneTextExtraLargeStyle}" />
            </StackPanel>
            <TextBlock
               x:Name="Email"
               Text="{Binding Email}"
               Margin="0"
               Style="{StaticResource PhoneTextSubtleStyle}" />

         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

 

Finally, we need to handle the event of the user clicking on one of the listed customers and responding by going to the Details page, which we will look at in the next mini-tutorial.

 

The complete source code for this mini-tutorial is available here.

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.

9 Responses to Windows Phone From Scratch #19 – MVVM Light Toolkit Soup To Nuts #4

  1. Jordan says:

    Great sample but I couldn’t see anything about Cleanup. With view first resolution, what makes sure that the view model disposes when a view closes?

  2. Anthony Geoghegan says:

    This is a really good series. Keep up the good work.

    However I think there’s a typo in the supplied source code for this example. The Customer class constructor “phone” parameter is never assigned to the Phone property. Instead there’s a cyclic reference Phone = Phone.

  3. @satish
    Satish, I’m not 100% certain I understand what you are getting at, but will look over the posting and try to formulate a coherent response as soon as I can.

  4. @Jeff B
    Your comments were totally fine, and thanks for the kind words.

  5. @Seth
    You are very kind, and in the spirit of no good deed goes unpunished, please do tell your friends and tweet about it; traffic is the currency in blogs 🙂

  6. Seth says:

    @Josh – on me too I guess then! It is that good
    @Jesse – thanks.

  7. satish says:

    Hi Jesse,
    I have asked this question already in twitter. In your tutorial you have binded a property Customers..
    Q1) what will happen if you have a Typo in your Property (ie) Obviously binding will produce an error at run time… and there are lot of ways to find it as well… But It would be great if we use the Asp.net MVC View Concept Such us strongly Typed view like
    http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx — as shown in the Blog Post will Help us avoiding lot of error with this Binding.. making it strongly Typed has lots of benfit Like testablity,ViewModel Creation become Genrics enabled..
    Can you please Mail me back the answer.. it will be very helpful …

  8. Jeff B says:

    I am also very happy with this series. You are providing great content for the community. I apologize for my comment on your book/movie collection.

  9. Josh says:

    This series continues to be great. I’m finding myself watching my Google Reader feed all afternoon, waiting for the next installment. (This is also probably a commentary on me, but still…)

Comments are closed.