WPF Application using MVVM In C#

Kailash Chandra Behera | Friday, June 26, 2020

Introduction

Here in this blog, we will learn how to create an WPF application using MVVM in C# and bind model data to WPF different controls.

WPF Application using MVVM in C#

Getting Started

The WPF is the short form or Windows Presentation Foundation, it is a free and open-source graphical subsystem similar to WinForms and originally developed by Microsoft for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of . NET Framework 3.0 in 2006.

The WPF features make Model-View-ViewModel(MVVM) a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it.

how to bind viewmodel to view in wpf

WPF Application using MVVM In C#

The Model-View-ViewModel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform.

The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than the view and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

WPF application using MVVM in C#

MVVM Elements in WPF

  1. Model :

    The model layer defines the types that represent your business data. This includes everything required to model the core app domain, and often includes core app logic. This layer is completely independent of the view and view-model layers, and often resides partially in the cloud. Given a fully implemented model layer, you can create multiple different client apps if you so choose, such as UWP and web apps that work with the same underlying data.

  2. View :

    The view layer defines the UI using XAML markup. The markup includes data binding expressions (such as x:Bind) that define the connection between specific UI components and various view-model and model members. Code-behind files are sometimes used as part of the view layer to contain additional code needed to customize or manipulate the UI, or to extract data from event handler arguments before calling a view-model method that performs the work.

  3. View-Model:

    The view-model layer provides data binding targets for the view. In many cases, the view-model exposes the model directly, or provides members that wrap specific model members. The view-model can also define members for keeping track of data that is relevant to the UI but not to the model, such as the display order of a list of items. The view-model also serves as an integration point with other services such as database-access code. For simple projects, you might not need a separate model layer, but only a view-model that encapsulates all the data you need.

WPF application using MVVM in C#

Demonstration

In the demonstration, we will see how to bind data with WPF controls (TextBox, ListBox) and use of MVVC command. Here we will display the selected item data of ListBox separately in different TextBox.

A list of employees is bound to the Listbox to list out the details of employees when user select any employee form the ListBox then the details of the employee will be displayed in the below of ListBox separately in different TextBox.

Follow the below steps to create WPF application using MVVM in C#

  1. Open Microsoft Visual Studio then click on Create new project from the Start Page or you can use the File menu.

  2. The New Project window will appear, find and choose WPF Application (.NET Framework) then click next button

  3. Name the application, here I have given name as myMvvmapp then click on OK button.

  4. The WPF project will be created, expand the Solution Explorer.

  5. Right click on the project name then Add one folder and rename it to Model.

  6. Add another folder and rename to View.

  7. Again add another folder and rename it to ViewModel.

  8. Right click on the Model folder and add new class, rename the new class to Employee. Remove all the content of the class and copy the Model class from below the blog and past inside the class.

  9. Again right click on the ViewModel folder and add new class, rename the new class to EmployeeViewModel. Remove all the content of the class and copy the ViewModel(EmployeeViewModel) class from below the blog and past inside the class.

  10. Right click on the View and add new Window and give any name, open the xample file. Go down, copy the grid control code from View:XAML and replace with the grid code of window.

     <!--Replace this grid code with new code-->  
       <Grid>  
       </Grid>  
       <!--End-->  
    
  11. Copy the below code and past it above the title property of Window. Basically the code is for taking reference of Interactivity.

     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"  
    
  12. Open the xaml.cs file of Window and in the constrocture, below the InitializeComponent() initialize the DataContext of Window and set the value as new instance of EmployeeViewModel. See the View:Xaml.cs code fore more details.

  13. Open the App.xaml file and remove the StartupUri then set the Startup value to "App_Startup". your App.xaml should look like below code.

     <Application x:Class="WpfApp1.App"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:local="clr-namespace:WpfApp1" Startup="App_Startup">  
       <Application.Resources>  
       </Application.Resources>  
     </Application>  
    
  14. Open the App.xaml.cs file and add the below code in the App class. Here in the code the MainWindow is called, if you are given other name to the window in View then replace the window with your window.
     void App_Startup(object sender, StartupEventArgs e)  
         {  
           View.MainWindow window = new View.MainWindow();  
           window.Show();  
         }  
    
  15. Your App class in App.xaml.cs should look like this below
     public partial class App : Application  
       {  
         void App_Startup(object sender, StartupEventArgs e)  
         {  
           View.MainWindow window = new View.MainWindow();  
           window.Show();  
         }  
       }  
    
  16. Now you are down with the WPF Application using MVVM In C#. Run the application and see the result.

Model for WPF Application using MVVM In C#

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace WpfApp1.Model  
 {  
   public class Employee : INotifyPropertyChanged  
   {  
     int _employeeNumber;  
     string _firstName;  
     string _lastName;  
     string _department;  
     string _title;  
     public Employee()  
     {  
       _employeeNumber = 0;  
       _firstName =  
       _lastName =  
       _department =  
       _title = null;  
     }  
     public int EmployeeNumber  
     {  
       get { return _employeeNumber; }  
       set  
       {  
         _employeeNumber = value;  
         OnPropertyChanged("EmployeeNumber");  
       }  
     }  
     public string FirstName  
     {  
       get { return _firstName; }  
       set  
       {  
         _firstName = value;  
         OnPropertyChanged("FirstName");  
       }  
     }  
     public string LastName  
     {  
       get { return _lastName; }  
       set  
       {  
         _lastName = value;  
         OnPropertyChanged("LastName");  
       }  
     }  
     public string Department  
     {  
       get { return _department; }  
       set  
       {  
         _department = value;  
         OnPropertyChanged("Department");  
       }  
     }  
     public string Title  
     {  
       get { return _title; }  
       set  
       {  
         _title = value;  
         OnPropertyChanged("Title");  
       }  
     }  
     public event PropertyChangedEventHandler PropertyChanged;  
     public override string ToString()  
     {  
       return String.Format("{0} {1} ({2})", FirstName, LastName, EmployeeNumber);  
     }  
     protected void OnPropertyChanged(string propertyName)  
     {  
       if (PropertyChanged != null)  
       {  
         PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);  
         this.PropertyChanged(this, args);  
       }  
     }  
   }  
 }  

View(XAML) for WPF Application using MVVM In C#

 <Window x:Class="WpfApp1.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"  
     xmlns:local="clr-namespace:WpfApp1"  
     mc:Ignorable="d"  
     Title="MainWindow" Height="450" Width="800">  
   <Grid>  
     <Grid.RowDefinitions>  
       <RowDefinition Height="110px" />  
       <RowDefinition Height="*" />  
     </Grid.RowDefinitions>  
     <ListBox Name="employeeListBox" ItemsSource="{Binding empList}" Grid.Row="0" SelectedItem="{Binding SelectedIndex}">  
       <i:Interaction.Triggers>  
         <i:EventTrigger EventName="SelectionChanged">  
           <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=employeeListBox, Path=SelectedValue}"/>  
         </i:EventTrigger>  
       </i:Interaction.Triggers>  
     </ListBox>  
     <Grid Grid.Row="1" DataContext="{Binding SelectedEmployee}">  
       <Grid.RowDefinitions>  
         <RowDefinition Height="*" />  
         <RowDefinition Height="*" />  
         <RowDefinition Height="*" />  
         <RowDefinition Height="*" />  
       </Grid.RowDefinitions>  
       <Grid.ColumnDefinitions>  
         <ColumnDefinition Width="80" />  
         <ColumnDefinition Width="*" />  
       </Grid.ColumnDefinitions>  
       <Label Grid.Row="0" Grid.Column="0">First Name</Label>  
       <Label Grid.Row="1" Grid.Column="0">Last Name</Label>  
       <Label Grid.Row="2" Grid.Column="0">Title</Label>  
       <Label Grid.Row="3" Grid.Column="0">Department</Label>  
       <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName, Mode=TwoWay}" />  
       <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName, Mode=TwoWay}" />  
       <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Title, Mode=TwoWay}" />  
       <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Department, Mode=TwoWay}" />  
     </Grid>  
   </Grid>  
 </Window>  

View(XAML.cs) for WPF Application using MVVM In C#

 using WpfApp1.ViewModel;  
 namespace WpfApp1  
 {  
   /// <summary>  
   /// Interaction logic for MainWindow.xaml  
   /// </summary>  
   public partial class MainWindow : Window  
   {  
     public MainWindow()  
     {  
       InitializeComponent();  
       this.DataContext = new EmployeeViewModel();  
     }  
   }  
 }  

ViewModel for WPF Application using MVVM In C#

 using Prism.Commands;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WpfApp1.ViewModel  
 {  
   public class EmployeeViewModel : INotifyPropertyChanged  
   {  
     public event PropertyChangedEventHandler PropertyChanged;  
     public List<Employee> empList { get; set; }  
     private Employee selectedEmployee;  
     public Employee SelectedEmployee  
     {  
       get { return selectedEmployee; }  
       set  
       {  
         selectedEmployee = value;  
         NotifyPropertyChanged("SelectedEmployee");  
       }  
     }  
     public DelegateCommand<object> MyCommand { get; private set; }  
     public EmployeeViewModel()  
     {  
       this.GetEmployees();  
       MyCommand = new DelegateCommand <object>(Excute);  
     }  
     private void GetEmployees()  
     {  
       this.empList = new List<Employee>();  
       this.empList.Add(new Employee() { EmployeeNumber = 1, FirstName = "John", LastName = "Dow", Title = "Accountant", Department = "Payroll" });  
       this.empList.Add(new Employee() { EmployeeNumber = 2, FirstName = "Jane", LastName = "Austin", Title = "Account Executive", Department = "Employee Management" });  
       this.empList.Add(new Employee() { EmployeeNumber = 3, FirstName = "Ralph", LastName = "Emmerson", Title = "QA Manager", Department = "Product Development" });  
       this.empList.Add(new Employee() { EmployeeNumber = 4, FirstName = "Patrick", LastName = "Fitzgerald", Title = "QA Manager", Department = "Product Development" });  
       this.empList.Add(new Employee() { EmployeeNumber = 5, FirstName = "Charles", LastName = "Dickens", Title = "QA Manager", Department = "Product Development" });  
     }  
     protected void NotifyPropertyChanged(string propertyName)  
     {  
       if (PropertyChanged != null)  
       {  
         PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);  
         this.PropertyChanged(this, args);  
       }  
     }  
     public void Excute(object employee)  
     {  
       SelectedEmployee = (Employee)employee;  
     }  
   }  
 }  

Related Articles

  1. Creating Application in Prism
  2. WPF Custom DataGrid in C#
  3. Custom RadioButtonListBox With Image
  4. RadiobuttonList in WPF
  5. Custom CheckedListBox in WPF
  6. Bootstrapper for Prism Application
  7. Create an ASP.NET Core Application in Azure
  8. Creating a simple ASP.NET Web Service
  9. AngularJS CRUD Operation
  10. Creating an AngularJS Application

Summary

In the above demonstration of blog WPF Application using MVVM In C#, we learned what is WPF, what is MVVC and how to bind data in WPF. Go through the entire code you will get idea about WPF and MVVM. I hope you have enjoyed it a lot.

Thanks