You can get the theoretical details of MVVM on the Intenet before moving further.

In this article, I am implementing WPF solution in MVVM approach for small requirement mentioned below:

Requirement

We need to display the Employee details based on the Employee id value entered by the user using MV-VM approach.

Solution

Let's create the sample WPF projects with the following items/files.

  • View: MainWindow.Xaml
  • MainWindow.Xaml.CS -->In MV-VM approach, codebehind plays very minor role.
  • View Model: SearchEmpVM.CS.
  • Model:Employee Class: EmpCls.cs – Created class file to hold the searched employee details.
    .

I will walk you through the Code of each entity in the order I have created.

EmpCls.cs (Entity class)

This class will contain the structure of Student entity. Here's the code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SampleWPFMVVM.Entity
  7. {
  8. class EmpCls
  9. {
  10. private int _empNo;
  11. public int EmpNo
  12. {
  13. get
  14. {
  15. return _empNo;
  16. }
  17. set
  18. {
  19. _empNo = value;
  20. }
  21. }
  22. private string _name;
  23. public string Name
  24. {
  25. get
  26. {
  27. return _name;
  28. }
  29. set
  30. {
  31. _name = value;
  32. }
  33. }
  34. private string _designation;
  35. public string Designation
  36. {
  37. get
  38. {
  39. return _designation;
  40. }
  41. set
  42. {
  43. _designation = value;
  44. }
  45. }
  46. private string _department;
  47. public string Department
  48. {
  49. get
  50. {
  51. return _department;
  52. }
  53. set
  54. {
  55. _department = value;
  56. }
  57. }
  58. }
  59. }
View (MainWindow.Xaml)

Write the Xaml code as below:

  1. <Window x:Class="SampleWPFMVVM.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. mc:Ignorable="d"
  7. xmlns:vm="clr-namespace:SampleWPFMVVM.ViewModel"
  8. Title="MainWindow" Height="350" Width="333"
  9. x:Name="Window">
  10. <Window.DataContext>
  11. <vm:SearchEmpVM />
  12. </Window.DataContext>
  13. <Grid>
  14. <Grid.RowDefinitions>
  15. <RowDefinition Height="auto" ></RowDefinition>
  16. <RowDefinition Height="auto"></RowDefinition>
  17. <RowDefinition Height="auto"></RowDefinition>
  18. <RowDefinition Height="auto" ></RowDefinition>
  19. </Grid.RowDefinitions>
  20. <StackPanel>
  21. <Grid Margin="0,51,0,-48" Grid.RowSpan="4">
  22. <Grid.RowDefinitions>
  23. <RowDefinition Height="auto"></RowDefinition>
  24. <RowDefinition Height="auto"></RowDefinition>
  25. </Grid.RowDefinitions>
  26. <Grid.ColumnDefinitions>
  27. <ColumnDefinition Width="auto"/>
  28. <ColumnDefinition Width="auto"/>
  29. </Grid.ColumnDefinitions>
  30. <Label Grid.Row="0" Grid.Column="0" Content="EmpId:"/>
  31. <TextBox x:Name="txtEmpId1" Text="{Binding ElementName=Window,Path=DataContext.EmpId,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Grid.Row="0" Grid.Column="1" ></TextBox>
  32. <StackPanel DataContext="{Binding SearchCls}" Grid.Column="1" Grid.Row="1">
  33. <GroupBox>
  34. <GroupBox.HeaderTemplate>
  35. <DataTemplate>
  36. <Label Content="Employee Information"/>
  37. </DataTemplate>
  38. </GroupBox.HeaderTemplate>
  39. <Grid >
  40. <Grid.RowDefinitions>
  41. <RowDefinition Height="26*"/>
  42. <RowDefinition Height="26*"/>
  43. <RowDefinition Height="26*"/>
  44. <RowDefinition Height="26*"/>
  45. <RowDefinition Height="26*"/>
  46. </Grid.RowDefinitions>
  47. <Grid.ColumnDefinitions>
  48. <ColumnDefinition Width="Auto"/>
  49. <ColumnDefinition Width="Auto"/>
  50. <ColumnDefinition Width="Auto"/>
  51. <ColumnDefinition Width="Auto"/>
  52. <ColumnDefinition Width="Auto"/>
  53. </Grid.ColumnDefinitions>
  54. <Label Grid.Row="0" Grid.Column="0" Content="Name:" Grid.ColumnSpan="3" />
  55. <TextBox Text="{Binding Name}" Grid.Row="0" Grid.Column="3" Width="174"/>
  56. <Label Grid.Row="1" Grid.Column="0" Content="Designation:" Grid.ColumnSpan="3"/>
  57. <TextBox Text="{Binding Designation}" Grid.Row="1" Grid.Column="3" Width="174"/>
  58. <Label Grid.Row="2" Grid.Column="0" Content="Department:" Grid.ColumnSpan="3" />
  59. <TextBox Text="{Binding Department}" Grid.Row="2" Grid.Column="3" Width="174"/>
  60. </Grid>
  61. </GroupBox>
  62. </StackPanel>
  63. </Grid>
  64. </StackPanel>
  65. </Grid>
  66. </Window>
Let me explain the important code lines highlighted in italic below,
  1. xmlns:vm="clr-namespace:SampleWPFMVVM.ViewModel" - This will import the namespace of our ViewModel "SearchEmpVM.CS".

  2. The following lines will bind the viewModel class as datacontext to the form:
    1. <Window.DataContext>
    2. <vm:SearchEmpVM />
    3. </Window.DataContext>
  3. The following code will bind the property "EmpId" of the viewModel class and fires the logic in the set procedure/block of the property of "EmpId" property.
    1. <TextBox x:Name="txtEmpId1" Text=" {Binding ElementName=Window,Path=DataContext.EmpId,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Grid.Row="0" Grid.Column="1" >
    2. </TextBox>
  4. The following code will bind the property "SearchCls" . This property will hold the object of the searched employees i.e "EmpCls" class,
    1. <StackPanel DataContext="{Binding SearchCls}" Grid.Column="1" Grid.Row="1">
  5. The following code will bind the property "Name" of the class "searchCls" (internal property of "EmpCls"), so whenever the Value is assigned to "Name" property the value will be displayed in the text box. Similarly we will bind the properties of the "EmpCls" to all the controls to display the selected employee values.
    1. <TextBox Text="{Binding Name}" Grid.Row="0" Grid.Column="3" Width="174"/>

ViewModel (SearchEmpVM.CS)

This will contain the business logic:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using SampleWPFMVVM.Entity; //namespace of Employee class
  8. namespace SampleWPFMVVM.ViewModel
  9. {
  10. class SearchEmpVM : INotifyPropertyChanged
  11. {
  12. List<EmpCls> EmpList = new List<EmpCls>();
  13. public SearchEmpVM()
  14. {
  15. // Add sample employee details into employee list
  16. EmpList.Clear();
  17. EmpList.Add(new EmpCls { EmpNo = 1, Name = "John", Department = "IT", Designation = "Developer" });
  18. EmpList.Add(new EmpCls { EmpNo = 2, Name = "Mark", Department = "IT", Designation = "Tester" });
  19. EmpList.Add(new EmpCls { EmpNo = 3, Name = "Robert", Department = "IT", Designation = "DB Developer" });
  20. }
  21. #region properties
  22. private EmpCls _searchcls = new EmpCls();
  23. public EmpCls SearchCls
  24. {
  25. get { return _searchcls; }
  26. set
  27. {
  28. _searchcls = value;
  29. RaisePropertyChanged("SearchCls");
  30. }
  31. }
  32. private int _empid;
  33. public int EmpId
  34. {
  35. get {
  36. return _empid;
  37. }
  38. set {
  39. _empid = value;
  40. RaisePropertyChanged("EmpId");
  41. PopulteEmpDetails(_empid);
  42. }
  43. }
  44. #endregion
  45. private void PopulteEmpDetails(int _empid)
  46. {
  47. SearchCls= EmpList.Where(x => x.EmpNo == _empid).Single();
  48. }
  49. #region INotifyPropertyChanged
  50. public event PropertyChangedEventHandler PropertyChanged;
  51. public void RaisePropertyChanged(string propertyName)
  52. {
  53. if (PropertyChanged != null)
  54. {
  55. PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  56. }
  57. }
  58. #endregion
  59. }
  60. }
Let us understand the code highlighted in the yellow color.

A . Our viewModel should implement interface to notify the client on binded property has changed .For more details

Refer the following link INotifyPropertyChanged.

B. Implement the method "RaisePropertyChanged" of interface "INotifyPropertyChanged" as highlighted in the above code

C. Call the method "RaisePropertyChanged" in the set procedures of all the properties which are binded to the controls.

For example:

Call as mentioned below:
  1. RaisePropertyChanged("EmpId"); //Pass the Property name as parameter
D. In the set property procedure of "EmpId", Pass the "_empid" to userdefined method "PopulteEmpDetails".

Since we have bind this property to the text box "EmpId" in the xaml file , whenever the user enter the value in the textbox the logic in the set procedure of "EmpId" property will be exited. Hence the Textbox value will be passed to our method ""PopulteEmpDetails" as in the following code.
  1. private int _empid;
  2. public int EmpId
  3. {
  4. get {
  5. return _empid;
  6. }
  7. set {
  8. _empid = value;
  9. RaisePropertyChanged("EmpId");
  10. PopulteEmpDetails(_empid);
  11. }
  12. }
E. The method "PopulteEmpDetails" will search the employee details from the list and set the List item to the property "SearchCls" as in the following code:
  1. private void PopulteEmpDetails(int _empid)
  2. {
  3. SearchCls= EmpList.Where(x => x.EmpNo == _empid).Single();
  4. }
In the Set procedure of the "SearchCls" property , we are assigning the value to the object "_searchcls" (which is the object EmpCls Class) i.e we are storing the searched employee details in the object of the "EmpCls" class.

Since we are binding the properties of the "SearchCls" property (i.e properties of the Class "EmpCls") to the textboxes, whenever the value is set to property ""SearchCls" then the properties of the "EmpCls" will be filled and then the textboxes will be filled with the same values as in the following image.

Output

EmpID

Hence, we implemented the required functionality as shown in the preceding image. Hope this article gives you the understanding on the basic implementation technique.