Saturday, February 20, 2010

WPF- Model-View-ViewModel

When it comes to WPF development, WPF provides us with its wide range of features to use. WPF is rich in features and give us more power to develop highly detailed and quailty UI 's. It give us more power and control over our development. On the other hand I came to WPF development from Windows Forms and it did really helps to start fresh with WFP and leave the Win Form concepts for Win Forms. But as I got deeper in WPF , I realized the power it has to offer. The features like Data Templating, Control Templating, Command Binding, Routed Events, Styles , Resources etc give us the exact power to create a line of bussiness
application with rich UI's.


One thing that brings all the features of WPF to there full powress is building the WPF apps with the use of Model-View-ViewModel pattern This pattern combines all the features of WPF and utilizes them to create the application that has clear seperation between the UI and Logic . Application is loosly coupled and testable when developed using the MVVM pattern.



















MVVM seperates the application design in three parts, Model, ViewModel, Views. Model act as the datarepositry and has the database connectivity or database mapped classes. It can be anything Linq-2-Sql, Entity Framework or any other ORM classes. Model are there and are not aware of anything (View Model or Views).



Next are the ViewModel classes that holds the logic for the actions that are done on Views . ViewModel classes are used to set up as the DataContext of the Views. In WPF , setting up datacontext of a control means that child element's also has its datacontext set as that of parent, if not exclusivly defined otherwise. By setting up the ViewModel as datacontext for a View we can set several datasources for various elements in Views .

void MainView_Loaded(object sender, RoutedEventArgs e)
{
_mainVM = new MainWinViewModel();
_mainVM.OnCloseEvent += new Action(_mainVM_OnCloseEvent);
this.DataContext = _mainVM;
}


View Model also simply encapsulate the Model classes. But its the CommandBinding feature of WPF that is utilized to communicate from Views to the ViewModel. As of the pattern, Views actually contains no code but only the xaml. That means we have to setup command binding in xaml for any user action to be delivered to the ViewModel to act upon. For this we define Commands in ViewModel and after setting it as the datacontext of the view , we bind the commands to various elements in View. These commands are known as Delegated Command or Relayed Command.


public class CustomersViewModel : ViewModelBase,
IDataErrorInfo
{
private Customer_Mst _custMst = null;
public string CustomerName
{
get
{
return _custMst.CustomerName;
}
set
{
_custMst.CustomerName =
value;OnPropertyChanged("CustomerName");
}
}



public class CustomersMgrViewModel :ViewModelBase
{
private ICommand _saveCommand = null;
private ICommand _deleteCommand = null;
private ICommand _updateCommand = null;
private ICommand _searchCommand = null;
private CustomersViewModel _customer =null;
public event Action OnReloadDataSource;

public ICommand SaveCommand
{
get
{
if(_saveCommand == null)
{
_saveCommand = new
DelegatedCommand(p => Save(), p => CanSave());
}
return _saveCommand;
}
}
private void Save()
{
try
{
using(CustomersDataContext context
= new CustomersDataContext())
{
Customer_Mst custMst = new Customer_Mst();
custMst.CustomerId = Customer.CusomerId;
custMst.CustomerName = Customer.CustomerName;
custMst.OrderId = Customer.OrderId;
context.Customer_Msts.InsertOnSubmit(custMst);
context.SubmitChanges();

if(this.OnReloadDataSource != null)
{
this.OnReloadDataSource();
}
ClearAll();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message,"Error");
}
}


Delegated/Relayed Command simply take delegate for Execute and CanExecute methods . ViewModel handles the action for these commands and perform any logic using Model classes .

public class DelegatedCommand : ICommand
{
readonly Action<-object> _execute;
readonly Predicate<-object> _canexecute;

public DelegatedCommand(Action<-object> execute)
: this(execute, null)
{
}
public DelegatedCommand(Action<-object> execute,
Predicate<-object> canexecute)
{
if (execute == null)
{
throw new ArgumentNullException("ExecuteNull");
}
this._execute = execute;
this._canexecute = canexecute;
}
public bool CanExecute(-object parameter)
{
return _canexecute == null ? true :
_canexecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public void Execute(-object parameter)
{
_execute(parameter);
}
}
}



View 's are simply the xaml file whose data context is set up as the relative ViewModel class. ViewModel provide the datasources for various elements in the View . View leverages the powerful features like styling , data templating, Resources, Control Templating etc to create unique UI's for the data from ViewModel data sources. Commands for the View Model act as the bridge between the View and the ViewModel.

There is no hard dependency between View and ViewMoldel, so ui designer can work independently and developer can code the logic. As previously said there is no code in Views and all the interaction code are handled by the ViewModel.



<-listbox name="lstCustomers" itemssource="{Binding}" issynchronizedwithcurrentitem="True">

<-stackpanel orientation="Horizontal" row="3" horizontalalignment="Right">
<-button name="btnSave" content="Save" width="70" command="{Binding Path= SaveCommand}">
<-button name="btnDelete" content="Delete" width="70" command="{Binding Path= DeleteCommand}">
<-button name="btnUpdate" content="Update" width="70" command="{Binding Path= UpdateCommand}">
<-button name="btnSearch" content="Search" width="70" command="{Binding Path= SearchCommand}">





Other resources. Book on MVVM by Josh Smith

No comments:

Post a Comment