Blogger news

Blogger templates

Saturday, February 19, 2011

MVVM Pattern (Model View ViewModel)

I am dedicating this post to my dear friends Sreelas and Sanjaykanth.

Before start reading this post i strongly recommend to go through DataBinding basics. Click here

The Model View View Model (MVVM) is an architectural pattern from Microsoft. MVVM commonly used with Silverlight and MVVM.

Elements of MVVM include:

Model: Model refers to an object model or to data access layer that represent that content.

View: View refers to all elements displayed in GUI such as TextBlock, buttons, DropDown etc.

View Model: ViewModel servers in data binding between the View and Model. View is directly binded to ViewModel and ViewModel expose data from model through properties. The ViewModel exposes public properties, commands.

Please see the image below,

The main purpose behind that is to separate the view, means the interface from the business logic by decoupling each other. The View Model which is normally a module, a class for example that ties the with the business logic and/or the data source.

The advantages of this Pattern are to render the business logic independent from the view for two main purposes, namely:
  1. For maintenance reasons, I mean if we want to entirely change the interface, we can do this easily, we just remove the current view and design the new view, all that we have to do is to bind the new view elements and controls' properties to the View Model module properties that's all.
  2. The second purpose is to render possible the test operations though unit testing, which is not possible within the classic implementation

Let us start with practical.

Follow the steps,

1. Open visual studio for Silverlight application and name it as MVVMSample. Click image below.

now you will get a window like below,

click ok.

2. The project will load and we can see a web project and a silverlight project. Ignore about web project now as we don't need it now to explain MVVM example. Consider MVVMSample project as our View.

3. Next step is to add another silverlight project for entities. we are going to explain our example with an Employe entity. Click image below,

3. Add a new class and name it Employe and create properties EmployeId and EmployeName. Please see the code below for Employe entity class,


public class Employe
{
public int EmployeId { get; set; }
public string EmployeName { get; set; }
}
build the entities project.

4. Create again new silverlight project and name it 'Model' as below,

4. Add a class to Model project and name it EmployeModel and add the class below to it,

public class EmployeModel
{
private List<Employe> _employes;
public List<Employe> Employes
{
get
{
return new List<Employe>
{
new Employe{EmployeId=100,EmployeName="Sreelas"},
new Employe{EmployeId=101,EmployeName="Sanjaykanth"},
new Employe{EmployeId=102,EmployeName="Serosh"}
};
}

set {
_employes = value;
}
}
}

we created a collection of Employe entities.

5. Again create new silverlight project and name it ViewModel as below,

6. Add a class inside ViewModel project and name it EmployeViewModel. copy the code below the new class created.

public class EmployeViewModel : INotifyPropertyChanged
{

EmployeModel empModel = new EmployeModel();
Employe empEntity = new Employe();

public EmployeViewModel()
{
EmployeName = Employes.FirstOrDefault(a => a.EmployeId == 100).EmployeName;

}

public List<Employe> Employes
{
get { return empModel.Employes; }
}

private string _employeName;

public string EmployeName
{

get
{
return _employeName;
}

set
{
_employeName = value;
FirePropertyChanged("EmployeName");
}

}

private ICommand _fireButtonClick;
public ICommand FireButtonClick
{

get
{
if (_fireButtonClick == null)
_fireButtonClick = new ExecuteCommand(() => ChangeName());
return _fireButtonClick;
}

}

private void ChangeName()
{
EmployeName = "Sanjaykanth";
}


#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void FirePropertyChanged(string propertyName)
{

if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

}

protected void FirePropertyChanged(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
{
PropertyChanged(this, args);
}

}

#endregion INotifyPropertyChanged Members
}

public class ExecuteCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public ExecuteCommand(Action execute) : this(execute, null)
{

}

#region ICommand Members


public ExecuteCommand(Action execute, Func<bool> canExecute)
{

if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{

return _canExecute == null ? true : _canExecute();
}

public event System.EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_execute();
}

#endregion ICommand Members
}

In the above code i will explain some thing. Will explain ICommand,Action etc in upcoming blog. Let me explain some thing which really need to understand.

public EmployeViewModel()
{
EmployeName = Employes.FirstOrDefault(a => a.EmployeId == 100).EmployeName;
}

In the constructor we are just initializing the property 'EmployeName' with the data from 'EmployeModel'. we are taking EmployeName with EmployeId=100. We are going to bind the property EmployeName to our View.

In the code above you can see a method "FirePropertyChanged", which will notify when ever the property changed to view. We have to call 'FirePropertyChanged' with the set method of property.

7. Open MainPage.XAML in MVVMSample project and add a 'TextBox' and a 'Button'. Bind 'TextBox. Please click image below for more details,


When the page load the value of TextBox will be 'Sreelas'. When the button clicked we will set the value of 'EmployeName' property to 'Sanjaykanth' and then value displayed in TextBox will be 'SanjayKanth'. So when the source property changes it affect the target property because the binding mode we given was TwoWay.

In the example TextBox.Text in the View (here MainPage.XAML) is binded with property of ViewModel. ViewModel gets value from Model.

This is simply an MVVM pattern.

No comments:

Post a Comment