How to Implement MVVM


Are you looking for code samples for MVVM design pattern? Find some good .NET examples for MVVM pattern in WPF using C# and .NET. I have briefly explained the concept of MVVM and have provided sample code.

MVVM : ModelViewViewModel



This article will help you to implement the MVVM presentation layer design pattern in wpf first we will discuss about the problem and then we will discuss how to implement it. This is simplest way you can have develop or implement MVVM design pattern in your application just have an start.

The Problem:

Designer and developer have dependency for working together and still need to maintain code behind and difficulty in unit testing as well.

Solution was introduce which is loosely coupled presentation layer style / best practice which will improve more reusability of resources with data templates, Ease of Unit Testing and save of time of designer and developer now both can work independently using Rich UI Design Tool like Expression blend and also code behind is not needed now which is major advantage.

View
It will contains User Interface related data mainly XMAL files.
E.g. Employee.Xmal

Model
Objects which will contain the actual data which is used.
E.g. Empoyee.cs

View Model
This is communicator between view and model. which will have properties which will bind in view.
E.g. List employeeList

Common and Resources
This is used to have or store command proxy and utility classes, resources and viewmodelbase which will implement INotify property change interface.

Implementation of MVVM pattern


See the steps involved in implementing the MVVM pattern in .NET and WPF:

Step 1 : Create a WPF Application Project

Step 2 : Create Logical Folders like
1. Model
2. ViewModel
3. View
4. Common
5. Resources

Step 3 : Define View
Here we need to add new window or user control which will contains the xmal page sample below :


<Window x:Class="View.EmployeeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="EmployeeView" Height="300" Width="300" >

<Grid>
<toolkit:DataGrid x:Name="EmployeeListGrid"
ItemsSource="{Binding EmployeeList}" >

<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn Header="Id" Width="63"
Binding="{Binding ID}" IsReadOnly="false" />
<toolkit:DataGridTextColumn Header="Name" Width="*"
Binding="{Binding theName}" IsReadOnly="false" />
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>

</Grid>
</Window>


Step 4 : Define Model by creating Employee.cs class file which will implement INotifyPropertyChanged

public class Employee : INotifyPropertyChanged
{
#region Private data Member

// Property variables
private int _id;


private string _theName;



#endregion

#region Constructors
public Employee()
{
}
#endregion

#region Properties
public int Id
{
get { return _id; }
set { _id = value; PropertyChangedEvent("Id"); }
}
public string TheName
{
get { return _theName; }
set { _theName = value; PropertyChangedEvent("TheName"); }
}
#endregion

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;
protected void PropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
#endregion
}



Step 5 : Define View Model by creating EmployeeViewModel.cs class

public class EmployeeViewModel : INotifyPropertyChanged
{

#region private Data Member

// Property variables
private ObservableCollection _EmployeeList;



#endregion

#region Constructor

public EmployeeViewModel()
{
this.InitilizeEmployee();
}

#endregion

#region Bindable Properties
public ObservableCollection EmployeeList
{
get { return _EmployeeList; }
set { _EmployeeList = value; PropertyChangedEvent("EmployeeList"); }
}
#endregion

private void InitilizeEmployee()
{
_EmployeeList = new ObservableCollection();
_EmployeeList.Add(new Employee { Id=1,TheName="Tony" });
_EmployeeList.Add(new Employee { Id = 2, TheName = "Ashish" });
_EmployeeList.Add(new Employee { Id = 3, TheName = "Ravinddra" });
_EmployeeList.Add(new Employee { Id = 4, TheName = "Navin" });
_EmployeeList.Add(new Employee { Id = 4, TheName = "Thomos" });
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;
protected void PropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
#endregion
}


Step 5 : Load Employee View on Application Start up in App.Xaml.cs file

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Initialize main window and view model
var mainWindow = new EmployeeView();
var viewModel = new EmployeeViewModel();
mainWindow.DataContext = viewModel;
mainWindow.Show();
}


Note : Here we can implement inotifiyproperty changed in common place like viewmodelbase which will treated as base class for all the view model in our application.And Commands are part of our view model so we can add it in view model and the proxy of Commands we can put into the common folder.


Comments

Author: rajesh kumar parbat05 Jul 2012 Member Level: Gold   Points : 0

Nice Article



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: