Click here to Skip to main content
11,481,404 members (62,428 online)
Click here to Skip to main content

How to use Commands in WPF

, 24 Oct 2013 CPOL 137.6K 6.1K 57
Rate this:
Please Sign up or sign in to vote.
This article shows how to use WPF Commands.

Introduction

In this article, we will talk about WPF Commands. When I develop a new application in WPF, I try to follow the MVVM Pattern (Model-View-ViewModel). To help me with it, I use the toolkit shared by Laurent Bugnion: MVVM Light Toolkit (Galasoft). The idea is the same with or without a toolkit.

Using the code

To show you how to use commands, we will create a simple application that saves some information about a person.

So a person can be described using these fields:

  • LastName
  • FirstName
  • Address
  • ZipCode
  • City

A Save button would call the SaveCommand and the Cancel button would call CancelCommand. We first create our model, adding a Person class in the Model directory. Keep things simple: 

public class Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
} 

Then we create our ViewModel: I will simply modify the one created by the template for MainWindow. I just edit it to add the properties needed:

public class MainViewModel : ViewModelBase
{
    private readonly Person _newPerson;

    private const string LastNamePropertyName = "LastName";
    public string LastName
    {
        get { return _newPerson.LastName; }
        set
        {
            _newPerson.LastName = value;
            RaisePropertyChanged(LastNamePropertyName);
        }
    }

    private const string FirstNamePropertyName = "FirstName";
    public string FirstName
    {
        get
        {
            return _newPerson.FirstName;
        }
        set
        {
            _newPerson.FirstName = value;
            RaisePropertyChanged(FirstNamePropertyName);
        }
    }

    private const string AddressPropertyName = "Address";
    public string Address
    {
        get
        {
            return _newPerson.Address;
        }
        set
        {
            _newPerson.Address = value;
            RaisePropertyChanged(AddressPropertyName);
        }
    }

    private const string ZipCodePropertyName = "ZipCode";
    public string ZipCode
    {
        get
        {
            return _newPerson.ZipCode;
        }
        set
        {
            _newPerson.ZipCode = value;
            RaisePropertyChanged(ZipCodePropertyName);
        }
    }

    private const string CityPropertyName = "City";
    public string City
    {
        get
        {
            return _newPerson.City;
        }
        set
        {
            _newPerson.City = value;
            RaisePropertyChanged(CityPropertyName);
        }
    }

    ///
    /// Initializes a new instance of the MainViewModel class.
    ///
    public MainViewModel()
    {
        _newPerson = new Person();
    }
}

Let's create the UI. We will have a simple form in MainWindow.xaml:

<Grid Height="195">
    <Grid.RowDefinitions>
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="42*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="122*" />
        <ColumnDefinition Width="296*" />
    </Grid.ColumnDefinitions>
    <Label Content="LastName" Grid.RowSpan="2" Height="28" HorizontalAlignment="Left" 
       Margin="40,5,0,0" Name="label1" VerticalAlignment="Top" />
    <Label Content="FirstName" Grid.Row="1" Grid.RowSpan="2" Height="28" 
       HorizontalAlignment="Left" Margin="40,5,0,0" Name="label2" 
       VerticalAlignment="Top" />
    <Label Content="Address" Grid.Row="2" Grid.RowSpan="2" Height="28" 
       HorizontalAlignment="Left" Margin="40,5,0,0" 
       Name="label3" VerticalAlignment="Top" />
    <Label Content="Code Postal" Grid.Row="3" Grid.RowSpan="2" 
       Height="28" HorizontalAlignment="Left" Margin="40,5,0,0" 
       Name="label4" VerticalAlignment="Top" />
    <Label Content="City" Grid.Row="4" Grid.RowSpan="3" Height="28" 
       HorizontalAlignment="Left" Margin="40,5,0,0" 
       Name="label5" VerticalAlignment="Top" />
    <TextBox Grid.Column="1" Grid.RowSpan="2" Height="23" HorizontalAlignment="Left" 
       Margin="20,5,0,0" Name="textBox1" VerticalAlignment="Top" 
       Width="120" Text="{Binding Path=LastName}" />
    <TextBox Grid.Column="1" Grid.Row="1" Grid.RowSpan="2" Height="23" 
       HorizontalAlignment="Left" Margin="20,5,0,0" Name="textBox2" 
       VerticalAlignment="Top" Width="120" Text="{Binding Path=FirstName}" />
    <TextBox Grid.Column="1" Grid.Row="2" Grid.RowSpan="2" Height="23" 
       HorizontalAlignment="Left" Margin="20,5,0,0" Name="textBox3" 
       VerticalAlignment="Top" Width="120" Text="{Binding Path=Address}" />
    <TextBox Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" 
       Margin="20,5,0,0" Name="textBox4" VerticalAlignment="Top" 
       Width="120" Text="{Binding Path=City}" />
    <TextBox Grid.Column="1" Grid.Row="3" Grid.RowSpan="2" Height="23" 
       HorizontalAlignment="Left" Margin="20,5,0,0" Name="textBox5" 
       VerticalAlignment="Top" Width="120" Text="{Binding Path=ZipCode}" />
    <Button Content="Save" Grid.Column="1" Grid.Row="6" Height="23" 
       HorizontalAlignment="Left" Margin="25,10,0,0" Name="button1" 
       VerticalAlignment="Top" Width="75" />
    <Button Content="Cancel" Grid.Column="1" Grid.Row="6" Height="23" 
       HorizontalAlignment="Left" Margin="120,10,0,0" Name="button2" 
       VerticalAlignment="Top" Width="75" />
</Grid>

Here is what it should look like:

Now, the main reason for this article: the Commands. We will create our two commands and then bind them to our buttons. How do we define a command? First, the command should implement the ICommand interface. Then, a Create method will create the command so that we can use it. Then, we find two methods: the first one, CanExecute, would check if the command can be executed, and the second one, Execute, will execute the command.

The Save Command:

public ICommand SaveCommand
{
    get;
    internal set;
}

private bool CanExecuteSaveCommand()
{
    return !string.IsNullOrEmpty(LastName);
}

private void CreateSaveCommand()
{
    SaveCommand = new RelayCommand(SaveExecute, CanExecuteSaveCommand);
}

public void SaveExecute()
{
    Person.Save(_newPerson);
}

If we look at the CanExecute method, we can see that the execution would be allowed only if there is a last name.

We now add the creation of the method in the constructor of our ViewModel:

public MainViewModel()
{
    _newPerson = new Person();
    CreateSaveCommand();
}

And we bind our command to the Save button:

<Button Content="Save" Grid.Column="1" Grid.Row="6" Height="23" 
   HorizontalAlignment="Left" Margin="25,10,0,0" 
   Name="button1" VerticalAlignment="Top" 
   Width="75" Command="{Binding Path=SaveCommand}" />

Let's launch the application and test this command.

When the application launches, the LastName is, of course, empty. And you can see that the Save button is disabled and we cannot save:

We add a last name and set the focus on the following textbox and we can observe that the Save button is now enabled. The condition in the CanExecute returns true!

If we delete the last name and change focus, the button will be disabled again.

Now, we add the Cancel command. It works the same way as the Save command but there is no requirement to allow the action. So, we will not use the CanExecute method:

public ICommand CancelCommand
{
    get;
    internal set;
}

private void CreateCancelCommand()
{
    CancelCommand = new RelayCommand(CancelExecute);
}

public void CancelExecute()
{
    LastName = string.Empty;
    FirstName = string.Empty;
    Address = string.Empty;
    ZipCode = string.Empty;
    City = string.Empty;
}

In the Execute method, we empty all the textboxes. Fill in the information and click on the Cancel button, all the textboxes will be cleared. Don't forget to call the CreateCancelCommand method in the constructor and to bind the command to the Cancel command. The constructor:

public MainViewModel()
{
    _newPerson = new Person();
    CreateSaveCommand();
    CreateCancelCommand();
}

Cancel button binding:

<Button Content="Cancel" Grid.Column="1" Grid.Row="6" Height="23" 
   HorizontalAlignment="Left" Margin="120,10,0,0" Name="button2" VerticalAlignment="Top" 
   Width="75" Command="{Binding Path=CancelCommand}" />

This is a very simple example of how to use Commands in WPF. Let's try it!

Points of Interest

WPF Commands are really useful in multiple ways. Here you saw how to use it and now you can try to discover what can be done with them.

History

  • August 9th, 2011: First post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nadege Rouelle
Architect
France France
I'm coding in .Net since 9 years, most with ASP.Net and SharePoint and a little using WPF, MVC, Windows Phone 8 and WinRT technology.
I have learned so much reading others experience and tutorials, or tips so I try to do the same, keeping learning from others of course.
You can also find my blog here : http://sharemstips.wordpress.com/
Follow on   Twitter

Comments and Discussions

 
QuestionWhere is ViewModelBase? Pin
azamsharp10-Jul-14 9:28
memberazamsharp10-Jul-14 9:28 
QuestionRelayCommand Implementation Pin
Member 930797820-May-14 18:05
memberMember 930797820-May-14 18:05 
Question[My vote of 1] Poor Example Pin
SledgeHammer0124-Oct-13 6:05
memberSledgeHammer0124-Oct-13 6:05 
AnswerRe: [My vote of 1] Poor Example Pin
daveslc15-Jan-14 7:07
memberdaveslc15-Jan-14 7:07 
AnswerRe: [My vote of 1] Poor Example Pin
Devoney27-Nov-14 10:03
memberDevoney27-Nov-14 10:03 
GeneralRe: [My vote of 1] Poor Example Pin
SledgeHammer0127-Nov-14 11:48
memberSledgeHammer0127-Nov-14 11:48 
GeneralMy vote of 5 Pin
fredatcodeproject24-Oct-13 3:21
memberfredatcodeproject24-Oct-13 3:21 
Questionmmmh Pin
Member 102086142-Sep-13 9:25
memberMember 102086142-Sep-13 9:25 
AnswerRe: mmmh Pin
Nadege Deroussen23-Oct-13 23:41
memberNadege Deroussen23-Oct-13 23:41 
QuestionError in the code , Pin
Sujit Bhujbal6-Mar-13 20:23
memberSujit Bhujbal6-Mar-13 20:23 
AnswerRe: Error in the code , Pin
Nadege Deroussen6-Mar-13 22:58
memberNadege Deroussen6-Mar-13 22:58 
AnswerRe: Error in the code , Pin
Member 1022371121-Aug-13 9:55
memberMember 1022371121-Aug-13 9:55 
GeneralRe: Error in the code , Pin
Nadege Deroussen23-Oct-13 23:41
memberNadege Deroussen23-Oct-13 23:41 
QuestionSource code does not compile Pin
mackan7020-Dec-12 2:40
membermackan7020-Dec-12 2:40 
AnswerRe: Source code does not compile Pin
Nadege Deroussen6-Mar-13 22:59
memberNadege Deroussen6-Mar-13 22:59 
QuestionHow about CommandBinding? Pin
Khanh Hua25-Sep-12 16:12
memberKhanh Hua25-Sep-12 16:12 
QuestionWhy the Save Button can't be Enabled after I fill in last name Pin
davidsun11111-Jul-12 9:42
memberdavidsun11111-Jul-12 9:42 
GeneralMy vote of 4 Pin
jalalx16-Jan-12 11:20
memberjalalx16-Jan-12 11:20 
QuestionHmmmm. Pin
Pete O'Hanlon9-Aug-11 23:48
protectorPete O'Hanlon9-Aug-11 23:48 
AnswerRe: Hmmmm. Pin
Nadege Deroussen15-Aug-11 7:34
memberNadege Deroussen15-Aug-11 7:34 
GeneralMy vote of 4 Pin
isaks9-Aug-11 11:50
memberisaks9-Aug-11 11:50 
GeneralRe: My vote of 4 Pin
Nadege Deroussen25-Aug-11 22:31
memberNadege Deroussen25-Aug-11 22:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 24 Oct 2013
Article Copyright 2011 by Nadege Rouelle
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid