How to bind ViewModel to View in WPF MVVM

We are watching step by step sample application on MVVM pattern. So let’s take below code

à  Take the new project in that adds four folder naming as Model, ViewModel, View and Command. See the below screen


Structure of MVVM


Description :

Model: In model we can basically added the properties of the model

View Model: In that we can add code logic, command on controls for processing your request coming from View

Command: In that we create the command for execute process through view controls like Button, Combo Box, and radio button etc. We can fire the event of control on this class.

View: It is the UI of page. It is used to display the result.

Step By Step Adding of classes in WPF MVVM:

Step 1:  Right click on Model folder  on that add a class file name as Student,

Step 2: Right click on ViewModel folder on that add class file name as StudentViewModel

Step 3: Right click on View folder on that add wpf windows form name as StudentView

Step 4: Right click on Command folder on that add class file name as RelayCommand

 Write Code on respective classes each shown below with namespace

Student.cs :

MVVM student class


StudentViewModels.cs

Add namespace
using StudentMVVM.Models;
using System.Windows.Input;
using System.Collections.ObjectModel;


Student View Model MVVM

RelayCommand.cs:
Add namespace
using System.Windows.Input;

Student relay command

Finally add view

View


After writing above code in respective file.

Right click on App.xaml file from solution explorer à click on ViewDesigner.

App.xaml designer look like below



             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Views/StudentView.xaml">
   
         
   



Change the above code StartupUri=”MainWindow.xaml” to

StartupUri=” View/PurchaseOrder.xaml” 

Run the application the output should be like below 

Student form view

 When click on Add button the result should be like below screen

After add student data


Please feel free  to share your quarries in comment.

Post a Comment

Previous Post Next Post