Starting with Events in WPF and MVVM pattern using PRISM library

This article is written to address beginners who want to know how to start with events in MVVM. This article covers the click event for the explanation. Through the given small bullet steps in this article, a novice programmer can easily understand the flow-mechanism by seeing where and how to write the event handling related code part.

There are a lot of frameworks available with WPF like Gala Soft, PRISM and so on; in this article explanation, PRISM framework has been used in WPF MVVM.

Article will illustrate the whole process through simple steps with snapshots and bit of important explanation of that thing:

  1. Step by Step Project creation
  2. Explaination of View-model code

a) Step by Step Project Creation 

  1. Add New WPF library project in solution:
  2. Create the project structure by adding required items.
    Create new Folder with name “VIEWS” and under this folder create a view of any type either window or user control. For now, I am using control type window:
    With this our folder structure looks like below:
  3. Install one package for PRISM i.e. click on Tools > NuGet Package Manager > package manger solution
    And browse PRISM .CORE for our created library
  4. Open the Window1.xaml in order to write some controls. After writing xaml for performing click operation this is how code & UI looks: 
    Here I highlighted the bindings of text  box controls of First Name and Last Name which plays important role when we write anything in textbox and access this data in our corresponding view model properties.
  5. Now I am going to create View Model Folder and under that I will write the code for my View i.e. first name, last name and the click me button.

 

b) Some explanation about above view model code:

We created two similar name properties as we mentioned in view i.e. for first name and last name. And in order to capture the click of BUTTON I created a ICOMMAND event delegate with same name as we set in UI i.e. ”Event Command”

One thing you have seen in above code that I inherited a class EventBaseClass what’s the role of this class?

Whenever our view model interacts with WPF UI there is role of two way binding in order to perform this there is one event called INotifyPropertyChanged that we have to use on every view model we create ,that tells the view model properties that some value is updated from UI.

****NOTE: In order to connect the basic thing that everyone miss that we have to connect both View and View Model . For that open your window1.xaml.cs file and in the constructor bind data context with our view model. like below:

That's it! Hope you enjoyed the article.