Get Started MVVM Light With WPF (Separation Of ViewModel) - Part Two

In this demonstration, we will see how can we separate the business logic (ViewModel) from the WPF Application and put it in separate class library project and use it.

The idea behind the separation of ViewModel is reuse ability of ViewModel for many other XAML base projects.  

Note

Read previous article Getting started with MVVM Light with WPF before reading this one.

Step 1

We will add the new class library project inside the Business logic layer.



Step 2

Add the “MVVMLightLibs” package from NuGet. This package contains the set of components, which are required for ViewModel implementation in class library project.

“MVVMLightLibs” package is distinguished from the MVVMLight. MVVMLight contains all library & components but MVVMLightLibs contains subset of those components.




After successful installation, remove the “Class1.cs” file from the project.

Step 3

Copy ViewModel folder from WPFDemo Application to BusinessLogic class library project.



Modify all the namespaces in MainViewModel.cs and ViewModelLocator.cs, since these files are now a part of ClassLibrary project.

  1. namespace WPFDemo.BusinessLogic  
  2. {  
  3.     /// <summary>  
  4.     /// This class contains static references to all the view models in the  
  5.     /// application and provides an entry point for the bindings.  
  6.     /// </summary>  
  7.     public class ViewModelLocator  
  8. {  
  9. .  
  10. .  
  11. .   



Step 4

Now, add “Business Logic” class library project as reference to WPFDemo Application.




Step 5

Now, in App.xaml file on WPFDemo Application, add/modified the highlighted line, which will point to Business Logic project to instantiate ViewModelLocator class. 

  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.              xmlns:bl="clr-namespace:WPFDemo.BusinessLogic;assembly=BusinessLogic"  
  10. >  
  11.   <Application.Resources>  
  12.     <ResourceDictionary>  
  13.           
  14.       <bl:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />  
  15.       
  16.     </ResourceDictionary>  
  17.   </Application.Resources>  
  18. </Application>   

In MainWindow.xaml

Now, you will see the Title property value of MainViewModel class, which will get update from the business logic class library project at design time highlighted below.


Output

Now, build and run the project to see the final output.