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.
- namespace WPFDemo.BusinessLogic
- {
-
-
-
-
- public class ViewModelLocator
- {
- .
- .
- .
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.
- <Application x:Class="WPFDemo.App"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:WPFDemo"
- StartupUri="MainWindow.xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- d1p1:Ignorable="d"
- xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:bl="clr-namespace:WPFDemo.BusinessLogic;assembly=BusinessLogic"
- >
- <Application.Resources>
- <ResourceDictionary>
-
- <bl:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
-
- </ResourceDictionary>
- </Application.Resources>
- </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.