Saturday, February 5, 2011

View Model 101

A View Model(VM) is a .cs file containing all the data required for the XAML file. It is like a code behind for a XAML file which holds all the data logic, data variables and methods required for the XAML UI layer(also referred as ‘View’) to show data.

Then, what's in the MainWindow.cs??

If you have a perfect VM design, thenMainWindow.cs should have ONLY the constructor with InitializeComponent() method. But, we cant achieve this most of the time. It often includes some complex event handler call back functions.

Here are some examples';

To achieve MainWindow.cs VM
On selecting a record from a datagrid full of patients; should show a Message Box with patient Info. On RecodActivated call back method with Message Box functionality. A datatable containing all the patient info.
On a event, load information from a file and also enable the associated datagrid Enable the datagrid A method to load information from file.

Most of the event handling can be done through XAML; Expression Blend 4 is mature enough to enable/disable/converter values using data binding.

Before we start, read about Properties and INotifyPropertyChanged.

ONLY the public Properties and public methods of VM are accessible by the View/XAML file. You can create Properties with code snippets prop or propfull

Sample VM,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace ViewModelDatabinding
public class ViewModel : INotifyPropertyChanged

#region Property Changed Event

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));


private string
public string FirstName
get { return firstName; }
set { firstName = value; OnPropertyChanged("FirstName"); }

private string lastName;
public string LastName
get { return lastName; }
set { lastName = value; OnPropertyChanged("LastName");}

private double age;
public double Age
get { return age; }
set { age = value; }

public ViewModel()
FirstName = "Uday";
LastName = "Thummalapalli";
Age = 25;

public void Update()
FirstName = "Dr. Uday";
LastName = "Genius";
Age = 29;


No comments: