Nico's digital footprint

I grew up in the nineties, that makes me awesome by default

A practical guide to MVVM (Light)

by Nico

You don’t have to look very far into the pits of the internet to find that there are still a lot of devs with questions on how to build a Windows / Windows Phone app with the MVVM pattern. In this article I’m going to explain my way of working. The libraries I use, how and why I use them. I hope this will clear some of the doubts others are having and helps you get on the right MVVM track.

What is MVVM?

Let’s start with walking through what MVVM is exactly. Feel free to skip this part if you already know because this has been discussed on almost every tech related website Glimlach

Let’s start with a diagram.


In MVVM there are three main parts, the Views, the Model and the ViewModels. The Model are just your basic POCO classes, nothing to fancy in there. The Views are your XAML files, the visual aspect of the application. The ViewModels are classes that get data from your data service classes and shape it into something the view is expecting.

Why these three parts? it’s a matter of seperation of concerns, the View doesn’t need to know where the data is coming from or in what format it’s delivered by the service. The only thing the View cares about is where it can get its data and it assumes that the data will be in the correct format. It gets that data from the ViewModel (or VM in short) through databinding. The View can make the VM do stuff by sending Commands its way, so View and ViewModel can interact with each other. The ViewModel reacts on those commands and requests data from the services, where that data comes from (in-memory, API, whatever, …) doesn’t matter for the VM, as long as it gets what it’s expecting.

Now, why would you use this? As mentioned before, it makes your code much cleaner by seperating the logic out of the View into the VM. It also makes the entire application much easier to unit test. You can just write tests against the ViewModels, since they are just normal .NET classes.

The endless discussion of code behind

There’s a small war among developers going on about MVVM. MVVM states that no code should exist in the code-behind of a view (for example MainPage.xaml.cs). Some people cling onto this statement, others take it as a “if you can”.

Here’s my opinion on the subject: MVVM is a design pattern, meaning that it’s a set of guidelines. Guidelines, as in “not set in stone”. Sometimes you need to jump through a lot of hoops to get something done in the VM while it’s much easier in the View. If you run into such a situation: decide if it’s worth spending time and research into the subject (and blog about it after you find the solution Knipogende emoticon). Another situation is things that have to do with the view. Things like changing a state in the Visual State Manager when switching from landscape to portrait, this is something that you can take to the ViewModel but in my opinion the VSM is pure View business, it has nothing to do with the ViewModel so that’s something I typically put into code behind.

As you can tell, the discussion isn’t really worth it. Just do whatever feels right for you (if you’re working in a team, make sure everyone is on the same page about this).

Let’s get started

Enough chit-chat, let’s get to the practical side of things. For this article I’m going to go with a Windows Phone 8.1 Silverlight project but a lot of the stuff here is applicable to any XAML technology, even ranging back to Windows Phone 7.

We’ll start with a blank slate, a brand new project started from the Blank App template. First thing you need to do when developing an MVVM application is add your MVVM stuff, either by adding a framework like Caliburn or by adding a toolkit with helper classes like MVVM Light (or by building your own of course). My weapon of choice in MVVM is always MVVM Light. Why? Because it’s a toolkit rather than a framework, it leaves a lot of the responsibilities in the hand of the developer. Frameworks like Caliburn rely more on conventions and that’s something I personally do not like. Other people have other preferences over this, so choice whatever feels right for you. For this article I’m using MVVM Light.

Let’s start by adding MVVM Light to the project. As with any good library, it’s on NuGet. If you search for MVVM Light on NuGet you’ll get some results, so what to pick? (I’ve marked the official MVVM Light NuGet packages in the screenshot).

Let’s go over them, top to bottom. The first one is the one I usually use. It adds the MVVM Light libraries to your project, creates a folder for the viewmodels, creates the MainViewModel and ViewModelLocator (more on this in a bit) and instantiates the ViewModelLocator in App.xaml. Quite a lot of work all done for you by the power of NuGet and PowerShell. The second NuGet package just adds the libraries to your project but it doesn’t create any folders or classes. The third package is the same as the second but as a Portable Class Library, use this one if you’re adding ViewModels in a PCL.

I usually go with the first one because of all the initial setup that occurs. Let’s add that package and have a look at the Solution Explorer.

For starters, NuGet added three libraries to the project. Why three? The first one is the actual MVVM Light library, the second one contains a bunch of extras like EventToCommand and SimpleIOC. In case you’re wondering why these are in a separate library, and where that Microsoft.Practices.ServiceLocation lib comes from, here’s Laurent’s answer to that:

“The Extras assembly exists because EventToCommand requires a reference to System.Windows.Interactivity, while ButtonBaseExtensions, RelayCommand, Messenger etc do not need it. Some people are reluctant to add references to assemblies if they can avoid it. So for those people who don't need EventtoCommand, they onlu use the base assembly, and the others who want the whole program can add Extras.

Cheers, Laurent”

Let’s take a look at the generated code files, starting with MainViewModel (I removed some of the comments for brevity)

Code Snippet
  1. namespace MvvmDemo.ViewModel
  2. {
  3.     public class MainViewModel : ViewModelBase
  4.     {
  5.         public MainViewModel()
  6.         {
  7.             ////if (IsInDesignMode)
  8.             ////{
  9.             ////    // Code runs in Blend --> create design time data.
  10.             ////}
  11.             ////else
  12.             ////{
  13.             ////    // Code runs "for real"
  14.             ////}
  15.         }
  16.     }
  17. }

Not much in there, but there doesn’t need to be. That’s what I like about MVVM Light, it keeps things simple and, well Light Glimlach. ViewModels are defined by creating a class that inherits from ViewModelBase, the name of a ViewModel (or VM in short) doesn’t need to end in “ViewModel” but I tend to do this to make them recognizable. We’ll be discussing the piece of code that’s commented out in a bit.

Next up is the ViewModelLocator class (again, removed some comments for brevity).

Code Snippet
  1. public class ViewModelLocator
  2. {
  3.     /// <summary>
  4.     /// Initializes a new instance of the ViewModelLocator class.
  5.     /// </summary>
  6.     public ViewModelLocator()
  7.     {
  8.         ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  10.         ////if (ViewModelBase.IsInDesignModeStatic)
  11.         ////{
  12.         ////    // Create design time view services and models
  13.         ////    SimpleIoc.Default.Register<IDataService, DesignDataService>();
  14.         ////}
  15.         ////else
  16.         ////{
  17.         ////    // Create run time view services and models
  18.         ////    SimpleIoc.Default.Register<IDataService, DataService>();
  19.         ////}
  21.         SimpleIoc.Default.Register<MainViewModel>();
  22.     }
  24.     public MainViewModel Main
  25.     {
  26.         get
  27.         {
  28.             return ServiceLocator.Current.GetInstance<MainViewModel>();
  29.         }
  30.     }
  32.     public static void Cleanup()
  33.     {
  34.         // TODO Clear the ViewModels
  35.     }
  36. }

So what is the ViewModelLocator? It’s the class that registers all the dataservices and viewmodels in the IOC container (if you don’t know what IOC is, read the next alinea, if you do know what it is you can skip the next part). The ViewModelLocator also provides properties for every ViewModel so we can easily bind a view to a viewmodel. The get part of these properties take the VM instance out of the IOC (again, read the next part for info on IOC) and returns it to the caller. Finally there’s a Cleanup method that you can use to cleanup viewmodels if you need to.

SideStep: IOC

Read this part if you’re not familiar with IOC, feel free to skip this part if you’ve already used IOC.
IOC, or Inversion Of Control, is often used in conjunction with DI or dependency injection. IOC is a technique used to make applications easily extensible and to increase the modularity. These goals can be achieved by using techniques like the Factory Pattern or Dependency Injection. With IOC and DI we can register classes in a so called container. Then, whenever we need one of those registered classes we can fetch the instance from the container instead of instantiating a new one, basically creating a Singleton effect. The big difference with a Singleton is that we can have dependency injection. If one of the classes contains a constructor that takes, for example, a dataservice as parameter and that dataservice is also registered in the container, the DI will inject the dataservice instance into the class with the constructor that takes in a dataservice. More over, we can use interfaces to register classes into the container. If that same class from before takes IDataService as a parameter, the registered instance of a class that implements IDataService will get injected into the constructor. This allows for a more abstract way of working.

Note: this was a basic explanation for IOC / DI. If you really want to get the hang of it, research it and use it, you’ll get it in no time. Some quick links to get you started (with thanks to Glenn Versweyveld for the links)

End of the sidestep: Marching on

MVVM Light has a built in IOC/DI framework called SimpleIoc. It’s exactly as the name implies, a very simple, basic framework but it gets the job done. In case that it wouldn’t fulfill your needs or you feel more comfortable with, for example, AutoFac, it’s really easy to swap SimpleIoc out and another framework in. See my “10 things you might have missed about MVVM Light” article from last year for a quick sample.

Okay, final part of the MVVM Light Powershell magic is something that happened inside the App.xaml. A resource was added to the Application.Resources

Code Snippet
  1. <Application.Resources>
  2.     <local:LocalizedStrings xmlns:local="clr-namespace:MvvmDemo" x:Key="LocalizedStrings" />
  3.     <vm:ViewModelLocator xmlns:vm="clr-namespace:MvvmDemo.ViewModel"
  4.                          x:Key="Locator"
  5.                          d:IsDataSource="True" />
  6. </Application.Resources>

The ViewModelLocator is added as an application resource, so it will get instantiated as soon as the application starts up. That means that all viewmodels and services are registered in the DI container right away. The resource is given a key so we can reference it when we set our datacontext in xaml.

Moving the View

MVVM Light puts the VM in the VM folder by default but the views are just hanging around in the project. If you don’t like this (as I do Glimlach) you can add a View folder and move the MainPage into that folder. Once it’s moved I have the habit of changing the namespace of MainPage to reflect the folder structure. This needs to happen in two places, xaml and code behind. In xaml find this line (it should be at the top)

Code Snippet
  1. x:Class="MvvmDemo.MainPage"

and change it to

Code Snippet
  1. x:Class="MvvmDemo.View.MainPage"

In code behind change the namespace to

Code Snippet
  1. namespace MvvmDemo.View

Right now, your application will compile perfectly but you will get a NavigationFailedException when launching. Open up the WMAppManifest.xml. On the Application UI tab is a textbox that says Navigation Page: MainPage.xaml. Navigating in Silverlight apps is still done using strings, so the compiler is happy here but at runtime the navigation target isn’t found at this location. Change it from MainPage.xaml to /View/MainPage.xaml and see if it works. If you entered the correct folder path the app should start.

Hooking up the View

Let’s get to the interesting part. We’re now ready to hook our view up on the viewmodel. This can be done from code behind or from XAML. I prefer the XAML way because it gives you some intellisense when binding to properties on the viewmodel, since the XAML designer knows of the datacontext if it’s defined in XAML.

This is what we need to add to the opening tag of a page to set the datacontext

Code Snippet
  1. DataContext="{Binding Main, Source={StaticResource Locator}}"

This is the full tag for reference:

Code Snippet
  1. <phone:PhoneApplicationPage x:Class="MvvmDemo.View.MainPage"
  2.                             xmlns=""
  3.                             xmlns:x=""
  4.                             xmlns:d=""
  5.                             xmlns:mc=""
  6.                             xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  7.                             xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  8.                             DataContext="{Binding Main,
  9.                                                   Source={StaticResource Locator}}"
  10.                             FontFamily="{StaticResource PhoneFontFamilyNormal}"
  11.                             FontSize="{StaticResource PhoneFontSizeNormal}"
  12.                             Foreground="{StaticResource PhoneForegroundBrush}"
  13.                             Orientation="Portrait"
  14.                             SupportedOrientations="Portrait"
  15.                             shell:SystemTray.IsVisible="True"
  16.                             mc:Ignorable="d">

If you don’t want to do it from XAML, it’s very easy to set it via Blend as well.

Open MainPage.xaml in Blend. Select PhoneApplicationPage in the Objects & Timeline pane.

In the properties pane, search for the DataContext Property and click on the white square next to it, select “Create databinding”

In the dialog that will popup, you’ll see the Locator key that we declared in App.xaml, Blend can interpret those resources and help you with binding to them. Select the Locator and you’ll see the Main property that is defined inside the ViewModelLocator (remember, the property that gets the MainViewModel instance from the container and returns it to the caller). Select that property and click OK, your binding is set!

Small thing about Blend: It’s AWESOME! period. If you don’t know how to use it, learn it. Learn to use it and you’ll automatically love it. Your apps will look much better and once you get the hang of using design time data you’ll get your design done much faster.

Adding our first binding

Let’s get some binding done! We’ll bind the title of the page to a property on the ViewModel just to get started. In the MainViewModel, Create a simple string autoproperty

Code Snippet
  1. public string Title { get; set; }

We’ll use the MainViewModel’s constructor to give this property some data. (line 3)

Code Snippet
  1. public MainViewModel()
  2. {
  3.     Title = "Hello World!";
  5.     ////if (IsInDesignMode)
  6.     ////{
  7.     ////    // Code runs in Blend --> create design time data.
  8.     ////}
  9.     ////else
  10.     ////{
  11.     ////    // Code runs "for real"
  12.     ////}
  13. }

Now onto the view, find the TextBlock for the page title and add the binding statement to the Text attribute (this can be done from Blend, just like the datacontext property, select the textblock, find the text property and add data binding)

Code Snippet
  1. <TextBlock Margin="9,-7,0,0"
  2.            Style="{StaticResource PhoneTextTitle1Style}"
  3.            Text="{Binding Title}" />

The Text property now contains a Binding statement. This is always set between curly braces, followed by the word Binding and the name of the property we’re binding to. At runtime the CLR will try to find a property with that name in the datacontext of the TextBlock, since we’re not specifying a DataContext on the TextBlock it will take that of its parent control, that way we’ll finally reach the MainViewModel where the Title property is waiting for us. Run the app and behold the wonders of databinding in an MVVM scenario.

Now this works but if we were to change the Title property as it is right now, it wouldn’t reflect on the page. A bound property isn’t monitored or polled for changes, we need to trigger some sort of event to tell the subscribers that a property has changed and that they need to refresh their binding. Usually this is done by implementing INotifyPropertyChanged and calling the OnPropertyChanged event in the property’s setter. In the case of MVVM the INotifyPropertyChanged interface is already implemented in the ViewModelBase class, so all we have left to do is raise the event (or call a method that raises the event, that method is called RaisePropertyChanged and sits in the ViewModelBase) from the property’s setter.

Code Snippet
  1. private string _title;
  3. public string Title
  4. {
  5.     get { return _title; }
  6.     set
  7.     {
  8.         if (_title == value) return;
  9.         _title = value;
  10.         RaisePropertyChanged(() => Title);
  11.     }
  12. }

We check if the property has really changed to avoid refreshing bindings when it’s not needed, if it does change we raise the event. According to the INotifyPropertyChanged interface we need to pass the property name as a string. MVVM Light’s ViewModelBase has an overload that takes a Func<string> so we can rely on intellisense to get the name of the property right. And with this we have a real databinding that will update the view when changed. Also, if you open MainPage in Blend now, you’ll notice that the binding is executed in design time as well. That’s one of Blend’s biggest strengths.

Using real fake data

Okay, so we now have databinding all set up, our MVVM structure is in place. Let’s build something that resembles an actual app. Create a Model folder in your project and add a Person class to it.

Code Snippet
  1. public class Person
  2. {
  3.     public string Picture { get; set; }
  4.     public int Age { get; set; }
  5.     public string Name { get; set; }
  6.     public string Company { get; set; }
  7.     public string Email { get; set; }
  8.     public string Phone { get; set; }
  9. }

Now to get some data I’ve used a website called json-generator to generate 15 instances of this class in Json format. You can download the JSON file I’ve used here

I placed the json in a static field in a static public class so my dataservice can easily get to it. I use this to simulate what could be a REST call in a real application. (if you want to know more about creating and calling REST services, read my article)

Add a folder called Services to the project and add an interface called IDataService.

Code Snippet
  1. public interface IDataService
  2. {
  3.     IEnumerable<Person> GetAll();
  4.     IEnumerable<Person> Get(Func<Person, bool> predicate);
  5.     Person GetByName(string name);
  6. }

The interface defines methods to fetch all the persons, to get a filtered set of persons by passing a predicate into a Where clause or fetch a specific person by name.

We’ll end up with two implementations of this interface. Let’s start with the first one, this one will be used at runtime and will query the actual service (the hardcoded JSON in this case, just assume it’s a call to a REST service). The first implementation is easy, the constructor fetches and deserializes the json. The methods then query that resultset.

Code Snippet
  1. public class DataService : IDataService
  2. {
  3.     private IEnumerable<Person> _persons;
  5.     public DataService()
  6.     {
  7.         _persons = JsonConvert.DeserializeObject<IEnumerable<Person>>(Data.Data.Json);
  8.     }
  10.     public IEnumerable<Person> GetAll()
  11.     {
  12.         return _persons;
  13.     }
  15.     public IEnumerable<Person> Get(Func<Person, bool> predicate)
  16.     {
  17.         return _persons.Where(predicate);
  18.     }
  20.     public Person GetByName(string name)
  21.     {
  22.         return _persons.FirstOrDefault(person => person.Name == name);
  23.     }
  24. }

Very basic data service, but enough to get my point across. Now it’s time to revisit the ViewModelLocator. When you look at the constructor of the ViewModelLocator you’ll notice that it contains a block of code that’s commented out.

Code Snippet
  1. public ViewModelLocator()
  2. {
  3.     ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  5.     ////if (ViewModelBase.IsInDesignModeStatic)
  6.     ////{
  7.     ////    // Create design time view services and models
  8.     ////    SimpleIoc.Default.Register<IDataService, DesignDataService>();
  9.     ////}
  10.     ////else
  11.     ////{
  12.     ////    // Create run time view services and models
  13.     ////    SimpleIoc.Default.Register<IDataService, DataService>();
  14.     ////}
  16.     SimpleIoc.Default.Register<MainViewModel>();
  17. }

That piece of code is exactly what we need. Why? Because it checks if the code is being executed in runtime or in design time. As I’ve mentioned before, the Blend and Visual Studio designers execute the code whenever a page is loaded into the designer. We can use that to hook up dummy data. The ViewModelBase class from MVVM Light contains a static boolean that tells us if we’re in design mode. We can use this to either register DataService in the container or a design time version of DataService (which we’ll build in a minute).

Uncomment the code so it looks like this (don’t worry about the DesignDataService error, the class doesn’t exist yet but it’s the next step.

Code Snippet
  1. public ViewModelLocator()
  2. {
  3.     ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  5.     if (ViewModelBase.IsInDesignModeStatic)
  6.     {
  7.         // Create design time view services and models
  8.         SimpleIoc.Default.Register<IDataService, DesignDataService>();
  9.     }
  10.     else
  11.     {
  12.         // Create run time view services and models
  13.         SimpleIoc.Default.Register<IDataService, DataService>();
  14.     }
  16.     SimpleIoc.Default.Register<MainViewModel>();
  17. }

In the Services folder, add a class called DesignDataService and make it implement IDataService.

Code Snippet
  1. public class DesignDataService : IDataService
  2. {
  3.     private List<Person> _persons;
  5.     public DesignDataService()
  6.     {
  7.         _persons = new List<Person>();
  8.         Random rnd = new Random();
  10.         for (int i = 0; i < 10; i++)
  11.         {
  12.             Person person = new Person
  13.             {
  14.                 Age = rnd.Next(10, 60),
  15.                 Company = "Design time company",
  16.                 Email = "",
  17.                 Name = "Design time person " + i,
  18.                 Phone = "+1 (846) 597-3140",
  19.                 Picture = ""
  20.             };
  22.             _persons.Add(person);
  23.         }
  24.     }
  25.     public IEnumerable<Person> GetAll()
  26.     {
  27.         return _persons;
  28.     }
  30.     public IEnumerable<Person> Get(Func<Person, bool> predicate)
  31.     {
  32.         return _persons.Where(predicate);
  33.     }
  35.     public Person GetByName(string name)
  36.     {
  37.         return _persons.First();
  38.     }
  39. }

I use a for loop to create 10 design time persons. Note that the GetByName method just returns the first person in the list. For design time data it doesn’t matter if the correct data is returned, we’re only using this data to get the visual aspect of the application right. Verify that the app still compiles and let’s get this thing injected.

Open the MainViewModel. Add a field for the IDataService and add IDataService as a parameter for the constructor.

Code Snippet
  1. private readonly IDataService _dataService;
  2. public MainViewModel(IDataService dataService)
  3. {
  4.     _dataService = dataService;
  5.     Title = "Hello World!";
  6. }

This is where constructor injection will come into play. SimpleIoc will inject the registered implementation if IDataService right here in the constructor, if you want to see this set a breakpoint in the constructor, open the app and inspect the parameter.

Now I want a property that contains the persons and bind this to some sort of list element so we get a nice, scrollable overview of persons. The perfect collection for bindable properties is an ObservableCollection. It notifies subscribers whenever an item is added so that those newly added items are shown immediately. Add the property to the MainViewModel

Code Snippet
  1. private ObservableCollection<Person> _persons;
  2. public ObservableCollection<Person> Persons
  3. {
  4.     get { return _persons; }
  5.     set
  6.     {
  7.         if (_persons == value) return;
  8.         _persons = value;
  9.         RaisePropertyChanged(() => Persons);
  10.     }
  11. }

We’re going to use the constructor of the MainViewModel to get some data in.

Code Snippet
  1. public MainViewModel(IDataService dataService)
  2. {
  3.     _dataService = dataService;
  4.     Title = "Hello World!";
  6.     IEnumerable<Person> persons = _dataService.GetAll();
  7.     Persons = new ObservableCollection<Person>(persons);
  8. }

The constructor of ObservableCollection<T> has an overload that takes in an IEnumerable<T> that can be used to seed the collection.

Blending it in

Let’s dive into Blend and get that design time data to work. Open MainPage.xaml in Blend. In the Data tab in Blend you’ll notice that MainViewModel shows up as Data Context, if you expand the tree structure you’ll find your ObservableCollection (if you don’t see it, switch back to Visual Studio and Build the solution, Blend doesn’t always update unless you build the project). Take the Persons property there and drag/drop it onto the design view (make sure MainPage.xaml is opened in design). When dragging over the design you should see this message appear.

Release the mouse button and a ListBox will be created and its ItemsSource wil lbe bound to that list on our MainViewModel. But it doesn’t look quite right.

This is common in Blend and is easily fixed, right-click the ListBox, go to Layout and select “Reset all”

Note: this is currently a ListBox, we are advised by Microsoft to use LongListSelector instead of ListBox for performance reasons. To change this, go into the xaml and change <ListBox… to <phone:LongListSelector.. Blend will keep working just like it’s doing now. For this article I’m just going to stick to ListBox but the way of working is the same.

We have a list of design time items now. Let’s run the app and see how it looks.

Notice how the data is different? The ViewModelLocator has registered the real DataService into the container so we’re now getting our real data instead of the design time data.

This doesn’t look very well, let’s see what we can do to change that. Blend makes changing item templates really easy, right-click the Listbox > “Edit Additional Templates” > “Edit Generated items (ItemTemplate)” > “Edit Current”

Have a look at the Objects & Timeline pane, you’ll see that it’s changed and shows the itemTemplate

From here you can create your entire layout, drag and drop properties from the Data tab onto the elements to create databindings. After about a minute I came up with this result.

The XAML for the itemtemplate:

Code Snippet
  1. <DataTemplate x:Key="PersonTemplate">
  2.     <Grid Margin="0,0,0,12">
  3.         <Grid.ColumnDefinitions>
  4.             <ColumnDefinition Width="Auto" />
  5.             <ColumnDefinition />
  6.         </Grid.ColumnDefinitions>
  7.         <Border Width="100"
  8.             Height="100"
  9.             HorizontalAlignment="Left"
  10.             VerticalAlignment="Top"
  11.             BorderBrush="Black"
  12.             BorderThickness="1">
  13.             <Image Source="{Binding Picture}" />
  14.         </Border>
  15.         <StackPanel Grid.Column="1">
  16.             <TextBlock Style="{StaticResource PhoneTextLargeStyle}" Text="{Binding Name}" />
  17.             <TextBlock Style="{StaticResource PhoneTextSubtleStyle}" Text="{Binding Company}" />
  18.         </StackPanel>
  19.     </Grid>
  20. </DataTemplate>

Result in runtime:

Splitting this post + Conclusion

I’m going to split this up in two posts as this one’s long enough already and my keyboard is getting tired Glimlach

Part two will focus on selecting a person from the list, navigating to a detail page, fetching and showing the details. Expect it to show up some time next week (I’ll update this post as well as soon is its ready).

In this first part I’ve discussed what MVVM was and why you should do it. I’ve shown you how I use MVVM Light and walked through the setup. We’ve also discussed design-time data and how Blend combined with this designtime data can help you getting a nice UI in a fast way.

The code for this first part can be found on my OneDrive.


.Net | Data | MVVM Light | Patterns | WP7 | WP8 | WinRT | XAML

Building a REST API and consuming it in WP8

by Nico

As a mobile developer we often need to consume some API in order to get data. In a lot of cases that API is made available to us by some third party, for example Twitter, Facebook, Flickr, ...  However, in some cases we are ourselves responsible for the data. In order to get the data from our datastore to our app we’ll need to build an API. In this article I’ll walk you through creating a basic API with the CRUD operations and consume it in a Windows Phone app.

For this post I’ll be using

  • ASP.NET WebApi 2.1
  • Visual Studio 2013
  • Microsoft Azure Websites
  • Windows Phone

The API will be build in WebApi 2.1 and hosted on Azure Websites. I’ve chosen Azure Websites because they offer 10 free websites and have great integration in Visual Studio 2013 update 1. Feel free to choose any other webhost, as long as they support MVC 5 you should be fine.

Setting up the API project

All right, let’s get started by building the API. In Visual Studio 2013 select File > New Project > Web > ASP.NET Web Application. In the next window, select Web API. If you’re deploying to Azure, check the “Create remote resources” box. This will create either an Azure Website or an Azure Virtual Machine for you. We’re not doing any authentication for this post, I’m saving that for a future post Glimlach, so leave it at No Authentication and click OK.

Visual Studio will create your project, tell Azure to create a Website and setup publish profiles for you. If you run this project you’ll get an ASP.NET MVC application with the default template but underneath it has also fired up a WebAPI. If you click the API link in the default template it will show you all available API calls (the WebApi template has a demo controller to get you started).

Now, for our API we’re going to create a database that holds famous quotes. Nothing fancy, just a database with one table that holds quotes. This is the Quote class

Code Snippet
  1. public class Quotes
  2. {
  3.     public int ID { get; set; }
  4.     public string Quote { get; set; }
  5. }

Time to add our API controller. If you’re familiar with MVC then this will look very familiar. WebAPI is basically MVC without the V. You have Models, you have controllers but instead of returning a view, the controllers return a Rest result, by default in JSON.

Right-click the controllers folder > Add > Controller. Select “Web API 2 controller with actions, using Entity Framework”. In the Model class dropdown select the Quotes class we’ve just created. The Data context drop down is where we can select our Entity framework context but that hasn’t been created yet. Click the + button next to the dropdown, select a name and click Add. Now we do have a context. Click Add and let Visual Studio create your Controller for you.

The newly created controller features all CRUD operations using the context we’ve just created to get to our Entity Framework. Before testing this, have a look in the Web.config file. You should find something like this not far from the top of the file

Code Snippet
  1. <connectionStrings>
  2.   <add name="RestDemoContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=RestDemoContext-20140327114532; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|RestDemoContext-20140327114532.mdf"
  3.     providerName="System.Data.SqlClient" />
  4. </connectionStrings>

This is the database connection that Entity Framework will use. It’s currently set to a local SQL Express database but a SQL Azure database has been created together with our project when we were first setting it up, so we’ll need to change this. Login to the Azure portal and go to Databases, find the created database for your project and select  “View SQL Database connection strings for ADO .Net, ODBC, PHP, and JDBC”.

Copy the ADO.NET connectionstring and paste it into the Web.config so that the line from before now looks like this

Code Snippet
  1. <connectionStrings>
  2.   <add name="RestDemoContext" connectionString=",1433;Database=RestDemo_db;User ID={Your_userID_here};Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
  3.     providerName="System.Data.SqlClient" />
  4. </connectionStrings>

Don’t forget to fill in your correct user ID and password. If you’ve set everything up, it’s time to try this out. Launch the project and navigate to the API link from the page header. It should now show you all available actions from your new controller. Click on the POST entry from the Quotes controller. This page shows you how a body from a POST request to this controller should look like. Let’s try it out in Fiddler.

Open Fiddler while your project is still running and go to the Composer tab. Set the method to POST from the dropdown and enter the url to your API endpoint. In my case this was http://localhost:36264/api/quotes. In the request headers field add this line

Content-Type: application/json

This will tell our API that the body contains JSON formatted data. In the request body we can copy/paste the sample data that the API page from the project gave us and fill in some nice quote.

  "ID": 1,
  "Quote": "you have failed me for the last time"

Click Execute and after a few seconds Fiddler should show a 201 result. HTTP code 201 means “Created” so our post was successful. Change the method to GET, clear the body and click execute again. Fiddler should show a 200. Select that line and the Inspectors Tab to see the result.


A closer look

Let’s take a closer look at the API methods.

Code Snippet
  1. // GET: api/Quotes/5
  2. [ResponseType(typeof(Quotes))]
  3. public async Task<IHttpActionResult> GetQuotes(int id)
  4. {
  5.     Quotes quotes = await db.Quotes.FindAsync(id);
  6.     if (quotes == null)
  7.     {
  8.         return NotFound();
  9.     }
  11.     return Ok(quotes);
  12. }

The first line is a comment (obviously Glimlach) that shows you how to call this method. The second line is an attribute to specify the expected content type in the response. Skip ahead to lines 8 and 11. These are helper methods found in the ApiController base class. When called they create a response with the correct HTTP code, 404 for not found or 200 for ok in this case, and set the content of the response.

We could add a second attribute to this method called HttpGet. Each of the verbs (GET, PUT, POST, DELETE) have an attribute version. You can use them freely here but the default template is working with a convention. Every method where the name starts with Get will be a GET method by default, the same for PUT, POST and DELETE.

Publish to Azure Websites

Publishing to your Azure website is as easy as right-clicking your web project (NOT the solution) and selecting publish. Let Visual Studio do its thing, your browser will open and your API is live on the internet. We can even debug live on the azure website by opening Server Explorer in Visual Studio > Azure > Websites > right-click your site > Attach Debugger (note that this works best when you deployed a debug build of your site.

Creating the app

Time to consume our fancy API. Create a new blank Windows Phone 8 application and add the following Nuget packages

  • Install-Package Microsoft.Net.Http
  • Install-Package Newtonsoft.Json
  • Install-Package MvvmLight

So what are these for? The first one gives us the HttpClient class which is a far superior way to do HTTP requests in Windows Phone than any class included in the SDK. It’s also a portable library so it makes your code very easy to port over to other platforms. because we’ll receive a JSON response from our API and we need to deserialize it back to an object. And MVVM Light because I just can’t live without it.

Getting data

We’ll start by requesting all quotes currently in the database. First, add the Quotes class from the API project to the phone project. Second, add a LongListSelector to the MainPage

Code Snippet
  1. <phone:LongListSelector ItemsSource="{Binding Quotes}">
  2.     <phone:LongListSelector.ItemTemplate>
  3.         <DataTemplate>
  4.             <TextBlock Style="{StaticResource PhoneTextNormalStyle}" Text="{Binding Quote}" />
  5.         </DataTemplate>
  6.     </phone:LongListSelector.ItemTemplate>
  7. </phone:LongListSelector>

Next, in the MainViewModel we’ll fetch the data and set it to Quotes (don’t forget to set MainViewModel as datacontext of MainPage).

Code Snippet
  1. private ObservableCollection<Quotes> _quotes;
  3. public ObservableCollection<Quotes> Quotes
  4. {
  5.     get { return _quotes; }
  6.     set
  7.     {
  8.         if (_quotes == value) return;
  10.         _quotes = value;
  11.         RaisePropertyChanged(() => Quotes);
  12.     }
  13. }
  15. /// <summary>
  16. /// Initializes a new instance of the MainViewModel class.
  17. /// </summary>
  18. public MainViewModel()
  19. {
  20.     FetchQuotes();
  21. }
  23. private async Task FetchQuotes()
  24. {
  25.     using (HttpClient client = new HttpClient())
  26.     {
  27.         var result = await client.GetAsync("");
  29.         result.EnsureSuccessStatusCode();
  31.         Quotes = new ObservableCollection<Quotes>(JsonConvert.DeserializeObject<IEnumerable<Quotes>>(await result.Content.ReadAsStringAsync()));
  32.     }
  33. }

Quotes is an ObservableCollection of type Quotes. FetchQuotes does all the heavy lifting here and is called upon initialization of the MainViewModel. It creates an instance of HttpClient (in a using statement, because HttpClient implements IDisposable). It calls our API endpoint that returns all quotes from the database. When it’s done fetching data we call EnsureSuccessStatusCode on the result. This method will throw an error if the returned HTTP code is not a success code, for example when we should receive a not found or bad request error. If everything went well we can read the result.Content as a string, this will give us the quotes in a JSON string format. We feed it into his deserializer and we’re done!

Now what good is having our own API when all we do is reading from it? Time to post some quotes! Add a second page and a way to navigate to that page. To keep things simple I’ve hooked this AddPage up to MainViewModel as datacontext. So I have 2 pages and 1 viewmodel. In the Viewmodel I create a new property that will hold the new quote.

Code Snippet
  1. public Quotes NewQuote
  2. {
  3.      get { return _newQuote; }
  4.      set
  5.      {
  6.          if (_newQuote == value) return;
  8.          _newQuote = value;
  9.          RaisePropertyChanged(() => NewQuote);
  10.      }
  11. }

The page contains a textbox that has a two-way binding to this property

Code Snippet
  1. <StackPanel x:Name="ContentPanel"
  2.             Grid.Row="1"
  3.             Margin="12,0,12,0">
  4.     <TextBlock Style="{StaticResource PhoneTextNormalStyle}" Text="Quote" />
  5.     <TextBox Text="{Binding NewQuote.Quote, Mode=TwoWay}" />
  6. </StackPanel>

And to glue things together, there’s a save method in the Viewmodel that will POST this new quote to the API, clear the NewQuote property and refetch all properties, including the one we just saved.

Code Snippet
  1. public async Task SaveQuote()
  2. {
  3.     using (HttpClient client = new HttpClient())
  4.     {
  5.         HttpContent content = new StringContent(JsonConvert.SerializeObject(NewQuote));
  6.         content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  8.         var result = await client.PostAsync("", content);
  10.         result.EnsureSuccessStatusCode();
  11.     }
  13.     NewQuote = new Quotes();
  14.     await FetchQuotes();
  15. }

To do a POST we first need to prepare the content. In our case we’re going to send a JSON string so we need to convert our NewQuote into JSON and put it inside StringContent. Next step is setting the ContentType in the header, just like we did when using Fiddler a few steps ago. Call PostAsync on the HttpClient, ensure its success and we’re done. If all went well the api saved the quote, the app refetched all quotes and the new one should show up on the MainPage.


In this article I’ve shown the steps needed to build and consume a basic REST API using WebApi and Windows Phone 8. The code from the WP8 app is very generic and can be used on a lot of platforms, even for platforms where HttpClient isn’t available, the way of working, the headers, the expected HTTP codes, should all be the same.

The code for both the API and the app can be found on my OneDrive.


.Net | Azure | Data | WP8 | WinRT | REST

Data validation in Windows Phone 8

by Nico

Whenever you need to do data input you’re probably going to add some form of data validation. There is a ton of information out there on how to do this in Silverlight and WPF but information on Windows Phone 8 is rather hard to find. After doing some research on the topic I’ve landed on the Fluent Validation library available on Nuget and decided to write something on the subject myself. I’ve put together a quick sample, including integration with SimpleIoc in MVVM Light.

Adding the package

We start of with an empty solution, add the MVVM Light libraries to it, bind the datacontext of MainPage to MainViewModel as you would usually do. Once the MVVM setup is complete it’s time to add the Fluent Validation package to the project.

Install-Package FluentValidation

Fluent Validation is an open source project available on Codeplex

Fluent Validation has libraries for

  • .net 4.0
  • MVC 3
  • MVC 4
  • MVC 5
  • Portable

The settings of the portable class library are

Meaning that the implementation I’m about to show will work just as well on Windows Store apps, so +1 for code sharing!

Creating the Model

The demo app is a simple registration form, a new user will be able to enter his name, birthdate and country. We’ll build validation rules on those properties later on. We’ll only have one model class in this app, called Member.

Code Snippet
  1. public class Member
  2. {
  3.     public string Name { get; set; }
  4.     public DateTime BirthDate { get; set; }
  5.     public string Country { get; set; }
  6. }

Setting up the validation

There is some work involved in getting everything setup, don’t worry, it’s hardly rocket science.

We’re going to create a ValidaterFactory. We need this because we’re going to use SimpleIoc to inject the validators into the ViewModels. If you don’t want to do this you can just create the validators and instantiate them whenever you need one, the Codeplex page of Fluent Validation has great documentation on this.

A ValidatorFactory inherits from the ValidatorFactoryBase class included in the library

Code Snippet
  1. public class ValidatorFactory : ValidatorFactoryBase
  2. {
  3.     public ValidatorFactory()
  4.     {
  5.         //register the Validators
  6.         SimpleIoc.Default.Register<IValidator<Member>, MemberValidator>();
  7.     }
  9.     public override IValidator CreateInstance(Type validatorType)
  10.     {
  11.         return SimpleIoc.Default.GetInstance(validatorType) as IValidator;
  12.     }
  13. }

The constructor of the ValidatorFactory is where I’m registering all validators. You could do this in the ViewModelLocator as well, like any other class / repository / viewmodel but this keeps my VMLocator cleaner and keeps the validation logic a bit closer together.

The CreateInstance function needs to be overridden and returns the instance of the requested validator.

Building a validator

Almost there, in this step we’re building a validator for the Member class. A validator inherits from AbstractValidator<T> where T is the class you want to validate.

Code Snippet
  1. public class MemberValidator : AbstractValidator<Member>
  2. {
  3.     public MemberValidator()
  4.     {
  5.         RuleFor(member => member.Name).NotEmpty();
  6.         RuleFor(member => member.BirthDate).LessThan(DateTime.Today);
  7.     }
  8. }

In the constructor of the validator we can finally start to add some rules. In this case we’re saying that the Name property should not be empty and that the birthdate property should be before today’s date.

We’ll need to register this class into our IOC, so in ViewModelLocator add this line

Code Snippet
  1. SimpleIoc.Default.Register<ValidatorFactory>(true);

We pass in ‘true’ as parameter to make sure the object is instantiated at the moment of registration, that way all validators are registered in the IOC as well (as seen in the ValidatorFactory’s constructor).

As a reference, these are all the built in validators of Fluent Validation

  • NotNull
  • NotEmpty
  • NotEqual
  • Equal
  • Length
  • LessThan
  • LessThanOrEqual
  • GreaterThan
  • GreaterThanOrEqual
  • Predicate
  • RegEx
  • Email

Quite an impressive list, and probably most of what you’ll need. Just in case that the one that you need isn’t included, you can build your own, we’ll discuss that in a bit. Let’s get these rules to work first.

Validating data

So we have a factory, we have a validator, all are getting registered in our IOC, time to hook up the ViewModels and getting some validation done.

In the MainViewModel we add a property of type Member that we’ll bind against

Code Snippet
  1. private Member _newMember;
  2. public Member NewMember
  3. {
  4.     get { return _newMember; }
  5.     set
  6.     {
  7.         if (_newMember == value) return;
  9.         _newMember = value;
  11.         RaisePropertyChanged(() => NewMember);
  12.     }
  13. }

Next, we’ll add two fields, one for the validator and one for the save command

Code Snippet
  1. private ICommand _saveMemberCommand;
  2. private IValidator<Member> _validator;

Next up is the ICommand property for the Save Command

Code Snippet
  1. public ICommand SaveMemberCommand
  2. {
  3.     get { return _saveMemberCommand ?? (_saveMemberCommand = new RelayCommand(SaveMember)); }
  4. }

Before we dive into the SaveMember method, we’ll need to do some constructor injection and initialization.

Code Snippet
  1. public MainViewModel(ValidatorFactory validator)
  2. {
  3.     NewMember = new Member
  4.     {
  5.         BirthDate = DateTime.Today
  6.     };
  8.     _validator = validator.GetValidator<Member>();
  9. }

As a parameter we get our ValidatorFactory, using its GetValidator<T> function we can fill up the _validator field. NewMember gets instantiated and the BirthDate property is set to a default of today.

And last but not least, the SaveMember method

Code Snippet
  1. private void SaveMember()
  2. {
  3.     if (IsValid())
  4.     {
  5.         MessageBox.Show("Registration completed!");
  6.     }
  7. }
  9. private bool IsValid()
  10. {
  11.     ValidationResult validationResult = _validator.Validate(NewMember);
  13.     if (!validationResult.IsValid)
  14.     {
  15.         ShowErrors(validationResult.Errors);
  17.         return false;
  18.     }
  20.     return true;
  21. }
  23. private void ShowErrors(IEnumerable<ValidationFailure> errors)
  24. {
  25.     StringBuilder builder = new StringBuilder();
  27.     builder.AppendLine("The following errors occured:");
  28.     foreach (ValidationFailure error in errors)
  29.     {
  30.         builder.AppendLine("- " + error.ErrorMessage);
  31.     }
  33.     MessageBox.Show(builder.ToString(), "error", MessageBoxButton.OK);
  34. }

To validate an instance we call the Validate function on a validator for that type, in this case ‘Member’. That function returns a ValidationResult. ValidationResult contains a bool property IsValid and a list of errors that it found.

We iterate over this list and put every error into a StringBuilder to get a nice error message in a messagebox. If I try to save with an empty name and today’s date as birthdate I get this.

Our validation is working! But those messages could be a bit better. Fluent Validator provides us with options to adjust the property name or the entire message. Change the constructor of the MemberValidator to this

Code Snippet
  1. public MemberValidator()
  2. {
  3.     RuleFor(member => member.Name).NotEmpty().WithMessage("You should enter your name");
  4.     RuleFor(member => member.BirthDate).LessThan(DateTime.Today).WithName("date of birth");
  5. }

On line 3 we use .WithMessage(“”) to replace the default message by whatever we want. Line 4 replaces the default name of the property, the result is similar yet slightly different

Adding a custom validator

Let’s say that we want to add validation to the Country property. This property must have a value of either ‘Belgium’, ‘Netherlands’ or ‘Luxemburg’ (this is called the BeNeLux). Obviously, this isn’t included as one simple validator so we’ll just build it ourselves.

We’ll need a class that inherits from PropertyValidator and overrides the IsValid function.

Code Snippet
  1. public class CountryMustBeInBenelux : PropertyValidator
  2. {
  3.     public CountryMustBeInBenelux()
  4.         : base("{PropertyName} is not a Benelux country")
  5.     {
  7.     }
  9.     protected override bool IsValid(PropertyValidatorContext context)
  10.     {
  11.         if (context.PropertyValue == null)
  12.             return false;
  14.         string country = context.PropertyValue.ToString().ToLower();
  16.         return country == "belgium" || country == "netherlands" || country == "luxemburg";
  17.     }
  18. }

The string that we pass in to the base constructor is the default message that will be used for this validator. The IsValid function takes a parameter of PropertyValidatorContext. This will contain the property that we want to validate and its value.

Next, in the MemberValidator constructor we add the validation for the Country property

Code Snippet
  1. public MemberValidator()
  2. {
  3.     RuleFor(member => member.Name).NotEmpty().WithMessage("You should enter your name");
  4.     RuleFor(member => member.BirthDate).LessThan(DateTime.Today).WithName("date of birth");
  6.     RuleFor(member => member.Country).SetValidator(new CountryMustBeInBenelux());
  7. }

As you can see we need to use the SetValidator function to add our own validator.

The result now is this (I’ve entered a name and a valid birthdate to clean up the error list a bit)



In this article I’ve discussed the use of Fluent Validator to do data validation in Windows Phone 8 apps. I’ve used the portable version of the library so these examples should work just fine on Windows 8 as well.

The Fluent Validator library has many more options than what I’ve discussed here and they are all well documented, head over the the Codeplex page if you want to do more and deeper validation.

The sample project can be found on my SkyDrive


.Net | Data | Validation | Fluent | MVVM Light | NuGet | WP8 | Windows 8 | WinRT | XAML

  Log in

About the author


My name is Nico, I’m an MVP Windows Platform Development living in Belgium.
I’m currently employed as a .NET consultant at RealDolmen, one of Belgium’s leading IT single source providers.

I'm also founding member and board member of the Belgian Metro App Developer Network, a user group focussed on Windows 8 and Windows Phone development. If you're in Belgium feel free to drop by if we're doing an event.

Since June 2012 I'm a proud member of Microsoft's Extended Experts Team Belgium. And in February 2013 I became a member of DZone's Most Valuable Bloggers family.

In 2013 I became a book author and wrote "Windows 8 app projects, XAML & C# edition".

In 2014 I received the MVP award for the very first time.

I hope to get feedback from my readers either through comments, mail (, twitter, facebook, …












Month List