I hope you have some knowledge of WPF and XAML before starting.

MVVM pattern is called Model-View-ViewModel pattern where we have three major components named:-

It’s basically developed to provide the functionality of data binding in WPF and separate the presentation layer from data layer and logic layer like in MVC (Model View Controller).

Whereas Prism is used to create the loosely coupled components which can work independently in an easy way. There are two main authors who are actively working on Prism library named Brian Lagunas and Brian Noyes.

You can read more about Prism and download/ add from the link directly.

Now I will show you a demo to set the value in view model and show that value in the view.

Note: In this article I am using Visual Studio 2015.

Step 1: Create a project named ‘PrismMVVMTestProject’ of WPF application.

wpf

Step 2: Right Click on project and select ‘Manage NuGet Packages…

Packages

Step 3:

Prism.Unity

Step 4: Accept the terms and conditions,

terms and Condition

Prism library has been installed successfully.

library

Now you can see the newly added dlls in the reference section of the project.

dlls

Step 5: It’s a better approach to create the 3 different folders in the project for Model, View and View model respectively.

mvc

Step 7: Create pages in all folders,

Step 8:

Add the namespace named ‘Prism.MVVM’ in the TestModel page to inherit the class named ‘Bindable Base’. Create a property named Message where ‘ref‘ parameter allows you to update its value,

  1. using Prism.Mvvm;
  2. namespace PrismMVVMTestProject.Models
  3. {
  4. classTestModel: BindableBase
  5. {
  6. privatestring _Message;
  7. publicstring Message
  8. {
  9. get
  10. {
  11. return _Message;
  12. }
  13. set
  14. {
  15. SetProperty(ref _Message, value);
  16. }
  17. }
  18. }
  19. }

code

Step 9:

Step 10:

Add a label named lblMessage in the TestView page and bind its content with the model property name with some other properties of binding like Mode and UpdateSourceTrigger,

  1. <Label x:Name="lblMessage" HorizontalAlignment="Left"
  2. Content="{Binding TestModel.Message,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
  3. VerticalAlignment="Top"/>
code

Step 11:

Add PrismMVVMTestProject.ViewModels namespace and bind DataContext of TestView Page to the ViewModel named ‘TestViewModel’.
  1. using System.Windows;
  2. using PrismMVVMTestProject.ViewModels;
  3. namespace PrismMVVMTestProject.Views
  4. {
  5. ///<summary>
  6. /// Interaction logic for TestView.xaml
  7. ///</summary>
  8. publicpartialclassTestView: Window
  9. {
  10. public TestView()
  11. {
  12. InitializeComponent();
  13. this.DataContext = newTestViewModel();
  14. }
  15. }
  16. }

code

Step 12: Change the ‘StartupUri’ from default page ‘MainWindow’ to ‘TestView’ page,

code

Run the page and see the output:

output

Read more articles on WPF: