Getting Started With MVVM Light With WPF

MVVM stands for Model View ViewModel, MVVM light toolkit is architectural design that is based on MVVM design pattern. MVVM is in part about avoiding code-behind in the View class. It is very popular architectural design pattern for XAML based applications like WPF, Silverlight, Windows phone app etc.

MVVM allows the code reusing ability to the different applications, we only need to worry about the design of all applications and coding (that includes business logic) can be shared across all applications.

In other words, we create model and write all code, commands, events (Business logic) in ViewModel once and use that Model and ViewModel in all the applications. We just need to make separate and different Views for each and every applications.

For example, if you want an action to be taken in response to a button click, then you can either assign a Click event handler or assign the Command property to command methods if we want to create 3 different applications - desktop application in WPF, Web application in silverlight, and phone application in Windows phone or Xamarin.

Benefits of MVVM are code reuseability, easy maintenance, separation of data model, design and code, and clean architecture etc. 

Step 1

Create a blank solution.


Step 2

Add two layers - one for “Business Logic” for business layers and another “WPF App” for WPF Application.

Note - We will learn about “Business Logic” in the coming articles.


Step 3

Add WPF project in “WPF App” layer.


Step 4

Now, we will install the “MVVM Light” from nuGet package.


After successful installation, you will see the below messages in the output window.


Also, you will see the following assembly files in WPF project reference.

  • MvvmLight
  • MvvmLight.Extras
  • MvvmLight.Platform

Also, you will see one new folder added in project “ViewModel” that contains two files.

  • MainViewModel.cs
  • ViewModelLocator.cs

MainViewModel.cs is model for “MainWindow.xaml” and ViewModelLocator ViewModelLocator is declared as an object on our App.xaml page and it is a single object; and only one of them available to the application when it runs.

ViewModelLocator is the source for all our ViewModels in MVVM Light. For each ViewModel we'll have a property on the ViewModelLocator that allows us to get a ViewModel for a View.


In the app.xaml

You will also notice that a new XAML code is added in app.xaml file which is highlighted below.

  1. <Application x:Class="WPFDemo.App"   
  2.              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4.              xmlns:local="clr-namespace:WPFDemo"   
  5.              StartupUri="MainWindow.xaml"   
  6.              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  7.              d1p1:Ignorable="d"   
  8.              xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">  
  9.   <Application.Resources>  
  10.     <ResourceDictionary>  
  11.           
  12.       <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:WPFDemo.ViewModel" />  
  13.       
  14.     </ResourceDictionary>  
  15.   </Application.Resources>  
  16. </Application>   

Build and run the application to make sure that everything is setup correctly. 

Now, if you add a brake point in “ViewModelLocator.cs” for constructor to check when WPF application is access this class.


You will notice that this class is not instantiated and the constructor never calls.

To instantiate this “ViewModelLocator.cs” and make sure compiler hits the constructor, we will add for the binding for DataContext of MainWindow.xaml.

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

In MainWindow.xaml.

  1. <Window x:Class="WPFDemo.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.         xmlns:local="clr-namespace:WPFDemo"  
  7.         mc:Ignorable="d"  
  8.         Title="MainWindow" Height="350" Width="525"  
  9.         DataContext="{Binding Main, Source={StaticResource Locator}}">  
  10.     <Grid>  
  11.           
  12.     </Grid>  
  13. </Window>   

Now, run the application and you will find that application instantiated the “ViewModelLocator.cs”; just hit the constructor.


Now, we will add a property “Title” for MainWindows.xaml in MainViewModel.cs file and bind it with the title property of MainWindows.xaml. 

  1. using GalaSoft.MvvmLight;  
  2. namespace WPFDemo.ViewModel  
  3. {  
  4.     public class MainViewModel : ViewModelBase  
  5.     {  
  6.         /// <summary>  
  7.         /// Initializes a new instance of the MainViewModel class.  
  8.         /// </summary>  
  9.         public MainViewModel()  
  10.         {  
  11.             ////if (IsInDesignMode)  
  12.             ////{  
  13.             ////    // Code runs in Blend --> create design time data.  
  14.             ////}  
  15.             ////else  
  16.             ////{  
  17.             ////    // Code runs "for real"  
  18.             ////}  
  19.         }  
  20.   
  21.     }  
  22. }  
  23.   
  24.   
  25. using GalaSoft.MvvmLight;  
  26. namespace WPFDemo.ViewModel  
  27. {  
  28.     public class MainViewModel : ViewModelBase  
  29.     {  
  30.         /// <summary>  
  31.         /// Initializes a new instance of the MainViewModel class.  
  32.         /// </summary>  
  33.         public MainViewModel()  
  34.         {  
  35.             if (IsInDesignMode)  
  36.             {  
  37.                 Title = "Hello MVVM Light (Design Mode)";  
  38.             }  
  39.             else  
  40.             {  
  41.                 Title = "Hello MVVM Light";  
  42.             }  
  43.         }  
  44.   
  45.         public string Title { get; set; }  
  46.   
  47.     }  
  48. }   

For binding the Title property, press F4 for MainWindow.xaml.



Now, select the Title and click on the little square that is the indication for binding.


Select the “Data context” in Binding Type dropdown and choose the “Title (String)” property what we have added in “MainViewModel.cs”

And, you will see the binding like “Title="{Binding Title}" in XAML.

 

  1. <Window x:Class="WPFDemo.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.         xmlns:local="clr-namespace:WPFDemo"  
  7.         mc:Ignorable="d"  
  8.         Title="{Binding Title}"   
  9.         Height="350" Width="525"  
  10.         DataContext="{Binding Main, Source={StaticResource Locator}}" 
  11.     <Grid>  
  12.           
  13.     </Grid>  
  14. </Window>   

As soon as you complete the binding, you will see the “Hello MVVM Light (Design Mode)” in MainWindow.xaml.

Design time output


Because xaml supports the design.

ViewModelBase base class has property IsInDesignMode that returns true if the window is in design state, else it returns false.

So, our Main Window is in design mode and it will show the "Hello MVVM Light (Design Mode)".

  1. if (IsInDesignMode)  
  2. {  
  3.    Title = "Hello MVVM Light (Design Mode)";  
  4. }  
  5. else  
  6. {  
  7.    Title = "Hello MVVM Light";         
  8. }   

When we run the application, we’ll see the different title values for "Hello MVVM Light" 

Run time output

Up Next
    Ebook Download
    View all
    Learn
    View all