MVVM prescribes separating the nonvisual classes that encapsulate interaction logic, business logic and data from the visual classes that actually render things to the screen. This separation makes the code easier to maintain: first, it prevents the UI from becoming a monolithic class with display controls, interaction logic and business logic all stuffed in side by side; and second, it enables you to automate the testing of interaction logic and user interface mappings instead of relying on expensive, unreliable manual testing..
Introduction
This article explains how to use MVVM Pattern in WPF using Visual Studio 2013 RC
The Model View View Model (MVVM) is an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler. Largely based on the model–view–controller pattern (MVC), MVVM is a specific implementation targeted at UI development platforms which support the event-driven programming in Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages.
Lets start by creating a WPF Application
Step 1: Create a New Project Open visual studio 2013 RC -> click on File -> New Project -> Create new Wpf Application
Now create three folders in root application. Name should be Model,View,ViewModel and now add a new class in Model folder. Here i have given Student
Student.cs
using System.ComponentModel;
namespace WpfApplication1.Model
{
public class User : INotifyPropertyChanged
{
private int studentId;
private string firstName;
private string lastName;
private string city;
private string state;
private string country;
public int StudentId
{
get
{
return studentId;
}
set
{
studentId = value;
OnPropertyChanged("StudentId");
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
OnPropertyChanged("LastName");
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
OnPropertyChanged("City");
}
}
public string State
{
get
{
return state;
}
set
{
state = value;
OnPropertyChanged("State");
}
}
public string Country
{
get
{
return country;
}
set
{
country = value;
OnPropertyChanged("Country");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
Step 2:Now right click on ViewModel Folder and add a new class
StudentViewModel.cs
Here we have created a Student ViewModel with all the students List and created a Update command using
Icommand
using System.Windows.Input;
using System.Collections.Generic;
using System;
using WpfApplication1.Model;
namespace WpfApplication1.ViewModel
{
class StudentViewModel
{
private IList<Student> _StudentsList;
public StudentViewModel()
{
_StudentsList = new List<Student>
{
new Student{StudentId = 1,FirstName="Ramiz",LastName="Raja",City="Banglore",State="KA",Country="INDIA"},
new Student{StudentId=2,FirstName="Chris",LastName="Hammond",City="New York", State="NY", Country="USA"},
new Student{StudentId=3,FirstName="Naresh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
new Student{StudentId=4,FirstName="Veeresh",LastName="Singh",City="Noida", State="UP", Country="INDIA"},
new Student{StudentId=5,FirstName="Harsha",LastName="Vardhan",City="Ghaziabad", State="UP", Country="INDIA"},
new Student{StudentId=6,FirstName="Ritesh",LastName="Kumar",City="Mumbai", State="MP", Country="INDIA"},
new Student{StudentId=7,FirstName="Ritwik",LastName="Patel",City="Palwal", State="HP", Country="INDIA"},
new Student{StudentId=8,FirstName="Rama",LastName="Sagar",City="Hyderabad", State="AP", Country="INDIA"}
};
}
public IList<Student> Students
{
get { return _StudentsList; }
set { _StudentsList = value; }
}
private ICommand mUpdater;
public ICommand UpdateCommand
{
get
{
if (mUpdater == null)
mUpdater = new Updater();
return mUpdater;
}
set
{
mUpdater = value;
}
}
private class Updater : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
}
#endregion
}
}
}
Step 3:Now Lets create a view Right Click on View Folder and create a view'
MainPage.xaml
Here we have created the view and corresponding bindings
<Window x:Class="WpfApplication1.View.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="485" Width="525">
<Grid Margin="0,0,0,20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListView Name="StudentGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding Students}" >
<ListView.View>
<GridView x:Name="grdstudent">
<GridViewColumn Header="StudentId" DisplayMemberBinding="{Binding Student Id}" Width="50"/>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="80" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />
<GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" />
<GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" />
<GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" />
</GridView>
</ListView.View>
</ListView>
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />
<Label Content="Student Id" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,274" Name="lblStudent" />
<Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="lblLastname" VerticalAlignment="Top" />
<Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="lblFirstname" VerticalAlignment="Top" />
<Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate"
VerticalAlignment="Top" Width="141"
Command="{Binding Path=UpdateCommad}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" />
<Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="Country_Copy" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" />
<Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="City_Copy" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />
<Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="State_Copy" VerticalAlignment="Top" />
</Grid>
</Window>
Now Lets bind the Application to open on Startup
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
WpfApplication1.MainWindow window = new MainWindow();
StudentViewModel SVM = new StudentViewModel();
window.DataContext = SVM;
window.Show();
}
Conclusion
In this article we have learned how to use MVVM pattern in WPF