BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Commanding - Creating Custom Commands

The one hundred and sixty-fifth part of the Windows Presentation Foundation Fundamentals tutorial continues the description of commanding. This article explains the process for creating custom commands and binding them to controls.

Implementing the ICommand Interface

The method that we will use to create custom commands in this article is the most flexible. The commands are created as self-contained classes that implement the ICommand interface. This interface contains three key members:

  • Execute. The Execute method contains the command's functionality. This is run automatically when the user correctly interacts with a control, or presses a keyboard combination, that is linked to the command.
  • CanExecute. The CanExecute method is called by WPF to determine whether or not the command is currently available. It is executed when the user tries to launch the command and in response to certain events. If the method returns false, the command's Execute method will not be called.
  • CanExecuteChanged. The CanExecuteChanged event should be raised when the status of CanExecute changes. This let's WPF know to call CanExecute and update the status of controls that are linked to the command. As external factors can influence the availability of a command, it is not always possible to raise this event. However, there is a trick that you can use to simplify the process.

Let's create a very simple command that implements the interface in a basic manner. Create a new class file named, "InfoCommand". When the file is open, update the class's signature to make it public and to specify that it will implement ICommand, as follows:

public class InfoCommand : ICommand

We can start by adding the Execute method. This accepts an object that can be used to pass a parameter to the command. For the first example we will ignore the parameter and simply display a message box. Add the following method to the InfoCommand class:

public void Execute(object parameter)
{
    MessageBox.Show("Hello, world!");
}

For the CanExecute method, we'll make this command always available by returning true.

public bool CanExecute(object parameter)
{
    return true;
}

Finally, we need to add the CanExecuteChanged event, This must be present for the correct implementation of the ICommand interface, even though we will not raise the event manually for this command. Add the event, as follows:

public event EventHandler CanExecuteChanged;

The InfoCommand class now represents a reusable command that contains all of its own functionality and knowledge of when it can be executed.

Binding Controls to Commands

Once you have created a command that you wish to execute in response to user events, you need to provide some way for the user to call it. We will expose the command through the main window's data context as a property, then link it to a button using a binding expression.

Let's create an instance of the command within the NameList class first. Start by adding a backing field for the command. Add the following field to the NameList file, within the class's braces but outside of any existing member. Note that the field is initialised directly to a new InfoCommand object.

InfoCommand _infoCommand = new InfoCommand();

Next, add a read-only property that surfaces the command object. This will be the source for the binding.

public InfoCommand InformationCommand
{
    get { return _infoCommand; }
}

We can now add the binding to the main window's XAML. As with other data bindings, you use the Binding keyword and the path to the item to find. As the data context is set for the window and all of its child controls, the path to the command is simply the name of the property, "InformationCommand".

Update the XAML for the "Info" button to bind the command, as shown below. Note the binding expression used to bind the Command property of the button to the InformationCommand property from the data context.

<Button Grid.ColumnSpan="2" Grid.Row="4" Command="{Binding InformationCommand}">Info</Button>

Run the program to see the results. Clicking the Info button should display a message box.

14 June 2015