Wednesday, November 23, 2011

MVVM Pattern in WPF: A Simple Tutorial for Absolute Beginners


Introduction

As part of learning the MVVM pattern, I tried to search many sites and blogs and found most of them explained the pattern in a complicated way. After some research, I cracked the very basic steps in MVVM pattern, and here I am trying to write an MVVM tutorial for absolute beginners.
I don’t think much more time or words need to be spent for explaining the various parts of MVVM and the relationship between MVVM and WPF. If you travel to the depths of WPF, you will realize that MVVM is the best suitable pattern for WPF (you might not understand the difference between these two).
As a formal procedure, I am giving a simple diagram and definition for MVVM:
I start this tutorial with two examples: WpfSimple.csproj and WpfMvvmTest.csproj.
For the sake of simplicity, in the first project (WpfSimple.csproj), we are avoiding the Model object (an example with Model will come later).
In the example WpfSimple, the View contains just a Button and no code-behind, but the button click event is loosely bound with the ViewModel. The bindings between the View and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a View. If property values in the ViewModelchange, those new values automatically propagate to the View via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action.

The View

The following code snippets are from the WpfSimple application (available with the tutorial):
<Window x:Class="WpfSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfSimple"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click" 
                Height="23" 
                HorizontalAlignment="Left" 
                Margin="77,45,0,0" 
                Name="btnClick" 
                VerticalAlignment="Top" 
                Width="203"
                Command="{Binding ButtonCommand}" 
                CommandParameter="Hai" />
    </Grid>
</Window>
The ViewModel class used here is MainWindowViewModel, the object set as the DataContext of the View.

The ViewModel

The ViewModel class used over here is MainWindowViewModel.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace WpfSimple
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }

        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action(ShowMessage));
        }

        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}
You can see an empty code-behind file here. If you click on the button, it will prompt a message box, despite the lack of event handling methods in the Views. When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object act as an adapter that makes it easy to consume a ViewModel's functionality from a View declared in XAML.

RelayCommand

RelayCommand is the custom class which is implemented in the ICommand interface. You can use any name instead of RelayCommand. Its usage is as follows:

No comments:

Post a Comment