Home > C#, MVVM, Windows Phone, WinRT > Using MVVM Light in Universal Windows apps

Using MVVM Light in Universal Windows apps

02/05/2014

We all know that the best way to share code in Universal apps is through the MVVM pattern. Thanks to it, we can easily have different Views, tailored to each device, but with the same Models and View Models.

With MVVM Light, it’s straightforward to add MVVM support to our apps. Because of the way the Shared project works, in order to use this library in it, it is necessary to add its reference to both the platform specific project. Using NuGet, we need to search and install the MVVM Light libraries only package (MvvmLightLibs) in the Windows project and in the Windows Phone one.

Adding Mvvm Light from NuGet

Adding Mvvm Light from NuGet

Now we can create a ViewModels folder in the Shared project and define a simple ViewModel, for example:

public class MainViewModel : ViewModelBase
{
    public string HelloWorld
    {
        get
        {
            return "Hello World!";
        }
    }

    public MainViewModel()
    {

    }
}

Then, let’s add a ViewModelLocator class that provides access to view models:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel MainViewModel
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
}

The next step is to declare the ViewModelLocator in the shared app.xaml file, so that it will be visible in all our XAML pages:

<Application
    x:Class="App1.App"
    ...>

    <Application.Resources>
        <ResourceDictionary>

            <vm:ViewModelLocator x:Key="Locator" xmlns:vm="using:App1.ViewModels" />

        </ResourceDictionary>
    </Application.Resources>
</Application>

Finally, we need to set the DataContext of our pages. For example, if we are using the Blank Universal app template, we have two MainPage.xaml files, one in each project. In both of them we write:

<Page
    x:Class="App1.MainPage"
    DataContext="{Binding Source={StaticResource Locator}, Path=MainViewModel}"
    ...>

Now we can use the same view models (because they are contained in the Shared project) in Windows and Windows Phone views, sharing all the application logic.

Categories: C#, MVVM, Windows Phone, WinRT
  1. bill
    09/05/2014 at 21:54

    Thanks! Need this…

  1. 07/05/2014 at 10:25
  2. 08/05/2014 at 09:53
Comments are closed.
%d bloggers like this: