Learn Simple MVVM and Command Bindings in 15 Mins

Introduction

The most powerful WPF framework (Silverlight) can be built with the most optimal architectural pattern, MVVM. MVVM is a collaboration of Model, View, and View Model. And MVVM is specially introduced to simplify the event-driven programming of user interfaces. MVVM and the Presentation Model are both derived from the Model View Controller.

MVVM pattern component

  • Model: A domain model represents the real-time entity or an object as a data access layer.
  • View: It's a user interface, probably a front-end design.
  • View Model: It's simply a data representation of a Model using public properties and commands.
  • Binder: It's a data and command binding between a View and a View Model for a Model.

Structure of MVVM

Model Here I have used a person as a model that contains the name and age of the person. C#

namespace MVVM
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

View

It is a user interface design. Here I used it to list the people in a ListView.

XAML

<Window x:Class="MVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MVVM"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView x:Name="ListViewPerson" ItemsSource="{Binding}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}"></TextBlock>
                        <TextBlock Margin="10,0,0,0" Text="{Binding Age}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

View Model

A View Model consists of a collection of data bound with the UI, in other words, the View.

C#

namespace MVVM {
    public class ViewModel {
        public ObservableCollection<Person> People;

        public ViewModel() {
            People = new ObservableCollection<Person>();
            Person person = new Person() { Name = "Thiruveesan", Age = 20 };
            People.Add(person);
            person = new Person() { Name = "Marutheesan", Age = 21 };
            People.Add(person);
            person = new Person() { Name = "Sharveshan", Age = 22 };
            People.Add(person);
            person = new Person() { Name = "Kailash", Age = 23 };
            People.Add(person);
        }
    }
}

Add Data Context

C#

ViewModel vm = new ViewModel();
MainWindow mw = new MainWindow();
mw.DataContext = vm;

Binder

Here we are using command binding to operate when the button is clicked.

C#

namespace MVVM {
    public class ViewModel {
        public ObservableCollection<Person> People;
        public ViewModel() {
            People = new ObservableCollection<Person>();
            Person person = new Person() {
                Name = "Thiruveesan",
                Age = 20
            };
            People.Add(person);
            person = new Person() {
                Name = "Marutheesan",
                Age = 21
            };
            People.Add(person);
            person = new Person() {
                Name = "Sharveshan",
                Age = 22
            };
            People.Add(person);
            person = new Person() {
                Name = "Kailash",
                Age = 23
            };
            People.Add(person);
        }
        private ICommand _clickCommand;
        public ICommand ClickCommand {
            get {
                return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), true));
            }
        }
        public void MyAction() {
            Person person = new Person() {
                Name = "Magesh",
                Age = 24
            };
            People.Add(person);
        }
    }
    public class CommandHandler: ICommand {
        private Action _action;
        private bool _canExecute;
        public CommandHandler(Action action, bool canExecute) {
            _action = action;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter) {
            return _canExecute;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter) {
            _action();
        }
    }
}

XAML

<Button Height="50" VerticalAlignment="Bottom" Command="{Binding ClickCommand}"></Button>

Main window