If you are the new in MVVM pattern using Prism Library then you can follow my very first article to start the MVVM and add the dlls into the project from the following link:

Now, I will show you a demo to fire the click event of a button from the view in view model.

Note: In this article I am using Visual Studio 2015 and ‘Prism.Unity’ via nugget Packages.

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

project

Step 2:

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

solution

Step 3: Create pages in all folders,

Step 4:

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. class TestModel: BindableBase
  5. {
  6. private string _Message;
  7. public string Message
  8. {
  9. get
  10. {
  11. return _Message;
  12. }
  13. set
  14. {
  15. SetProperty(ref _Message, value);
  16. }
  17. }
  18. }
  19. }

code

Step 5:

a. Add the following namespaces on the TestViewModel page,

b. Create a property of TestModel class object where ‘ref‘ parameter allows you to update its value.

c. Attach command to the method which will act like event.

d. Set the message value ‘You Have Clicked the button’ as string in that method.

  1. using PrismMVVMTestProject.Models;
  2. using Prism.Mvvm;
  3. using System.Windows.Input;
  4. using Prism.Commands;
  5. namespace PrismMVVMTestProject.ViewModels
  6. {
  7. class TestViewModel: BindableBase
  8. {
  9. private TestModel testModel;
  10. public ICommand ClickCommand
  11. {
  12. get;
  13. private set;
  14. }
  15. public TestViewModel()
  16. {
  17. testModel = new TestModel();
  18. ClickCommand = new DelegateCommand(ClickedMethod);
  19. }
  20. public TestModel TestModel
  21. {
  22. get
  23. {
  24. return testModel;
  25. }
  26. set
  27. {
  28. SetProperty(ref testModel, value);
  29. }
  30. }
  31. private void ClickedMethod()
  32. {
  33. TestModel.Message = "You Have Clicked the button";
  34. }
  35. }
  36. }

code

Step 6:

Step 7:

Add PrismMVVMTestProject.ViewModels namespace and bind Data Context of TestView Page to the ViewModel,

  1. named‘ TestViewModel’.
  2. using System.Windows;
  3. using PrismMVVMTestProject.ViewModels;
  4. namespace PrismMVVMTestProject.Views
  5. {
  6. /// <summary>
  7. /// Interaction logic for TestView.xaml
  8. /// </summary>
  9. public partial class TestView: Window
  10. {
  11. public TestView()
  12. {
  13. InitializeComponent();
  14. this.DataContext = new TestViewModel();
  15. }
  16. }
  17. }

code

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

page

Run the page and see the output:

Output

After click on the button.

Output

Read more articles on WPF: