Using #mvvmlight with Windows 10 universal applications

.NET, Blend, MVVM, Phone, Technical stuff, Universal Windows Platform UWP, Windows 10, Windows Phone, XAML
See comments

Yesterday, Microsoft released to the public the development tools for Windows 10 (technical preview). With this release, you can start developing applications targeting the universal application platform (UAP).

Of course MVVM Light is present on this new platform too and allows you to build decoupled applications with the MVVM pattern. More than ever, XAML and the data binding system allow you to build applications in a fast and comfortable manner for a large number of devices with Windows 10.

Creating the new application

Note: You need Visual Studio 2015 for this demo!

After you install the Windows 10 development tools, you will see a new category in the “New Project” dialog in Visual Studio. Select the Blank Application (UAP) and give it a name, then click ok.

2015032401 Creating a new Windows 10 UAP

Adding MVVM Light

The nice thing with Windows 10 is that it just accepts Windows 8.1 PCLs without any changes. So you can just add the existing version of MVVM Light to this application. You can either use the mvvmlightlibs package (which contains only the libraries) or the mvvmlight package which also installs a ViewModelLocator and a MainViewModel. Let’s select this package for the demo here.

  • In the Solution Explorer, right click on the new Windows 10 UAP project you just created.
  • Select Manage Nuget Packages.
  • Nuget has a new UI now (see below). Select the nuget.org package source, and Search for mvvmlight.
  • Select the mvvmlight package and click Install.
  • After accepting the license, MVVM Light is added to your new Windows 10 application.

2015032402
New UI for Nuget

Using MVVM Light in your application

At this point, the only thing you need to do to fully use MVVM Light is to set the MainPage’s DataContext to the MainViewModel. The rest was done automatically by Nuget:

  • Nuget downloaded and added a reference to the MVVM Light assemblies
  • Nuget also added the ViewModelLocator in the Application.Resources.

To set the MainPage’s DataContext, simply open it in Visual Studio and modify the Page’s opening tag as shown below:

<Page x:Class="Win10Uap.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:Win10Uap"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      DataContext="{Binding Main, Source={StaticResource Locator}}">

For more information about the MVVM Light features, see the documentation page. You can also check the Windows 10 UAP sample corresponding to this article. This sample application has the following features:

  • ViewModelBase: The MainViewModel inherits from ViewModelBase and uses its methods (see MainViewModel.cs).
  • SimpleIoc: The DataService and the MainViewModel are handled by the IOC container (see ViewModelLocator.cs).
  • RelayCommand: The “Increment counter” button in the main page is databound to the IncrementCommand in the MainViewModel.
    • When called, this command increments a counter and sets the WelcomeTitle property.
    • This property raises the PropertyChanged event and the corresponding binding updates a TextBlock in the MainPage.
  • NavigationService: The “Navigate to page 2″ button in the main page is databound to the NavigateCommand in the MainViewModel. This triggers a navigation (using the MVVM Light NavigationService) to the second page.
    • If you enter a text in the TextBox labeled “Enter any text for nav…”, this text will be passed to the second page as a navigation parameter.
    • From the second page, the “go back” button will bring you back to the main page.
    • When running the app on Windows Phone, you can also use the device’s Back button to navigate back from the second page.
  • DialogService: The “Show a dialog” button on the main page will use the MVVM Light DialogService to display a dialog.
  • Messenger: The button labeled “Send message” in the main page sends a NotificationMessage. This message is handled in the App.xaml.cs, at the application level.
    • In App.xaml.cs, you can see the recipient method being registered on line 78 (HandleNotificationMessage).
    • This method executes the callback, which sends a string “Success (from App.xaml.cs)!” back to the MainViewModel.
    • In the MainViewModel, the message sending is done at line 75.
    • The callback is executed at line 80.
  • DispatcherHelper: A small clock is implemented.
    • The RunClock method starts in the MainViewModel at line 122.
    • Because it runs on a background thread, the DispatcherHelper is used to set the Clock property.
    • This property is bound to a TextBlock in the main page.
    • The DispatcherHelper is initialized in the App.xaml.cs on line 76.

Design time

As all MVVM Light applications, this one is “blendable”, i.e it is design-time friendly. To prove this, open the MainPage.xaml in Blend:

  • Right click on MainPage.xaml in the Solution explorer.
  • Select “Design in Blend”
  • Make sure that the MainPage is indeed open (in the current version, there seems to be some issues with that, and you need to open the MainPage manually).
  • See the application’s UI: Instead of “Welcome to MVVM Light”, you should now see “Welcome to MVVM Light [design].

This happens because of the switch in the ViewModelLocator.cs on line 23. Because ViewModelBase.IsInDesignModeStatic returns true in Blend, the DesignDataService is registered in the IOC container instead of the “production time” DataService. This is possible because both implement the IDataService interface.

Because Blend is able to run this code, and because SimpleIoc is able to function in Blend, the design-time text is rendered. Using the same technique, it is possible to render a whole design-time UI, including lists, data templates, etc. Note that Blend is able to simulate different screen sizes, as shown in the screenshot right below.

2015032409
Design time screen in Blend, 13’’ Desktop (1366×766)

2015032410
Design time screen in Blend, 4.5’’ Phone (480×800) 

Running the app

Because this is a universal application, it can run as is on multiple devices! Here I will show how to run this app on a Surface Pro 3 and on the Windows Phone emulator.

To run on the local machine (in my case Surface Pro 3), select “Local Machine” from the “Run” drop down menu (screenshot below). You can also use the Simulator if you prefer. If you want to run this on your attached Windows Phone (with Windows 10 installed), select “Device” (though I am not sure if that option works as of now). Finally, to test on a Windows Phone emulator, select the corresponding “Emulator” option.

2015032411
Selecting the right target to run the app

2015032403
Main page on Windows

2015032404
Second page on Windows

2015032405
Showing a message on Windows

2015032406
Main page on the phone

2015032407
Second page on the phone

2015032408
Showing a message on the Phone

What about a project template?

At this point, I am a bit behind with project templates. I will do my best to update the existing templates and add the missing ones (Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UAP) but in the mean time, you can create the app and add MVVM Light from Nuget as explained above.

Hopefully this will help you to get a head start with Windows 10 development on the universal application platform!

Happy coding
Laurent

Previous entry | Next blog entry

Responses to “Using #mvvmlight with Windows 10 universal applications”

  1. Tung Nguyen Thanh Says:

    Great Laurent,

    Thanks for sharing it. Hope project template release soon :)

  2. The Morning Brew - Chris Alcock » The Morning Brew #1828 Says:

    […] Using #mvvmlight with Windows 10 universal applications – Laurent Bugnion shares a look at building Windows 10 applications using MVVMLight, walking through the process of creating an application […]

  3. gluténmentes budapest Says:

    Its cool but I have to say that the WinRT platform is still a hard-to-use thing.

    I tried to install Win10pre+VS.NETpre but failed, I tried to develop universal apps under Windows 7 but it’s not supported…

  4. lbugnion Says:

    I am not sure it is unreasonable to ask that Windows 8 apps be developed on Windows 8, and Windows 10 apps on Windows 10 ;)

    What failed when you tried to install Windows 10?

  5. romeo Says:

    Hi Laurent, at the first launch i have this error:

    Could not find SDK “BehaviorsXamlSDKManaged, Version=12.0″.

    Is there any workaround?

  6. lbugnion Says:

    Ah yes, give me a moment and i will point you to the documentation for behaviors in Win10. Sorry

  7. romeo Says:

    I solvedcopying the extension SDKs from the Windows 8.1 Extension SDK location to the universal apps location—that is:
    From:
    C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1\ExtensionSDKs
    to:
    C:\Program Files (x86)\Microsoft SDKs\UAP\v0.8.0.0\ExtensionSDKs

  8. Aviad Sachs Says:

    Hi Laurent, Thanks for sharing this!

    I am porting a WPF app to Win8.1 but really want to port it to Win10, so this is promising! I use MVVM LIght in all 3 projects :)

    Would WinRT XAML Toolkit Nuget package will work also on Win10UAP do your opinion?

  9. How to install and try the Windows 10 preview … and start developing! | Enzo Contini Blog Says:

    […] Using #mvvmlight with Windows 10 universal applications […]

  10. Michael Sage Says:

    nuget.org was not in my list of nuget package sources. I had to go to tools -> options -> NuGet package manager -> Package Sources and turn on nuget.org to see MVVMLight packages

  11. lbugnion Says:

    Hi Michael,

    It’s a good point. Nuget.org is usually there by default but I should update the doc to make sure that it is clearly indicated.

    Thanks for the feedback,
    Laurent

  12. José G. Ramírez Says:

    A great job, MR. lbugnion.

    You have been the first-before the official pattern in Microsoft PRISM strive to carry MVVM or try it on Windows Apps 10.

    MVVM Light has been very intuitive to my projects. Would you continue to so.

    Thank you.

  13. Yannick Says:

    Hello,

    je viens de me remettre sur MvvmLight et UAP avec une grande joie …

    Super boulot au passage Mr. BUGNION.

    Cependant, j’ai un soucis au niveau du ViewModelLocator car le code suivant n’est pas reconnu par VS

    static ViewModelLocator()
    {
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    var nav = new NavigationService();
    nav.Configure(SecondPageKey, typeof(SecondPage));
    SimpleIoc.Default.Register(() => nav);

    SimpleIoc.Default.Register();

    if (ViewModelBase.IsInDesignModeStatic)
    {
    SimpleIoc.Default.Register();

    Le Design de Design.DesignDataService est souligné en rouge avec le message d’erreur qui me dit que je dois manqué d’une directive…

    Merci

  14. Russ Says:

    Hello,

    Using Visual Studio 2015 Enterprise. Created new Windows 10 Universal application. Added both mvvmlight and mvvmlightlibs using nuget. ViewModelLocator file was not created, nothing was added to resources. When trying to use it get:

    at System.Runtime.InteropServices.WindowsRuntime.ICommandAdapterHelpers.c__DisplayClass2.b__3(Object sender, EventArgs e)
    at System.EventHandler.Invoke(Object sender, EventArgs e)
    at GalaSoft.MvvmLight.Command.RelayCommand.RaiseCanExecuteChanged()
    at …MyViewModel.d__17.MoveNext()
    — End of stack trace from previous location where exception was thrown —
    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.c__DisplayClass2.b__3(Object state)
    at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()

  15. lbugnion Says:

    Hi,

    Unfortunately the Nuget team changed the implementation for UWP and decided not to support content files and the powershell script anymore. I am working with them to try to find workarounds. You can help me by tweeting @LWischik and letting him know that you miss content files in Nuget for UWP.

    I am also working on updating the documentation and samples and should have something for you after I am back from vacation.

    The other error is not something I have seen. Normally adding mvvmlightlibs alone should be enough for an UWP (since mvvmlight takes reference on mvvmlightlibs anyway). Then you need to add the content files manually (for example create a Win8.1 app, add mvvmlight and then check the ViewModel folder and App.xaml which was modified to include the ViewModelLocator.

    Sorry for the inconvenience. I was also surprised that the Nuget team removed content files. This was not discusses with the community.

    Laurent

  16. Dino Borogovac Says:

    Hi there MVVM light team. i wanted to add the latest nuget package to my emtpy UWP project but found out that there isn o viemodelbase and locator added to the project?! why?!

  17. lbugnion Says:

    Hi, Unfortunately the Nuget team changed the way that Nuget works for Win10 UWP apps, and does NOT support content files or scripts anymore. Please reach out to @LWischik on Twitter and let him know that this is a problem. They are thinking of changing the new policy. I will publish an article explaining how to add these files manually, stay tuned to this blog.

  18. Richard Says:

    Hi!

    Got an issue with relaycommand if I reference it in xaml it returns an object not set to an instance error:

    Xaml Internal Error error WMC9999: Object reference not set to an instance of an object.

    Hmm this used to work. Came back after an weekend in Rome and now this *lol*

  19. Richard Says:

    Well I found the problem. It’s more of an designproblem.

    My ViewModel contails at list och Items and all the jadda jadda for the navigationservice and so on. When binding the listview on the page I can’t get a reference to the NavigationCommand becouse i can’t reach the ViewModel only the List.

    Is the right way to solve the problem is to move the command to the list but it seems wrong to have obe viewmodel that’s contains a collection of viewmodels :)

  20. CodingNinja Says:

    Package install error : CommonServiceLocator.1.3 : Package restore failed。Rolling back “xxxx” package change.

  21. lbugnion Says:

    Hi,

    Not quite sure what you mean. Can you describe what you tried in order to get this error?

    Thanks
    Laurent

  22. andy Says:

    hello,
    do you have any guidance on code sharing between WPF and Universal apps using mvvmlight? PCLs, Shared Projects, etc.
    We’re starting a project for Windows 7 and would like to have architecture ready for migration to newer technologies like Universal apps.

  23. lbugnion Says:

    Hi,

    Personally I would put as much as possible in a PCL. Then if there are a few things that don’t fit, see what you can share at a file level (Add as Link in Visual Studio). Some things (XAML….) might just not be shareable but I think that with such an architecture you should be on a good track.

    HTH,
    Laurent

  24. Joel Josep Says:

    I tried install the Mvvm light 5.2.0 in windows 10 Universal App as said in this article , but even though the reference was added the folders (viewModel) and the ViewModelLocator could not be found . Also the code in App.xaml

    which use to be added automatically was not added as well.

    I use to use MVVM Light For windows Phone 8.1 Development and now i used the similar methods.

    But i couldn’t find any documentation for the new version installation in windows 10 UWP other than this article

    Can you help me?

    well it was not just me i recently found this on stackoverflow

    http://stackoverflow.com/questions/32186295/mvvm-light-cant-work-in-windows-10-universal-app

  25. Dimitris Says:

    I made an MVVM-Ready application for Windows Phone 8, based on this sample:
    http://bunsofcode.com/2016/03/12/mvvm-ready-application-windows-phone/

Comments for Using #mvvmlight with Windows 10 universal applications