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.

Completing the Example

Let's complete the example program by implementing the command that removes an item from the list. There is nothing new in the remaining code samples; we will use exactly the same techniques as above.

Start by creating a new class named, "RemoveCommand". Add the following code to the class:

public class RemoveCommand : ICommand
    public bool CanExecute(object parameter)
        var nameList = parameter as NameList;
        return nameList != null && nameList.SelectedName != null;

    public void Execute(object parameter)
        var nameList = parameter as NameList;
        var oldName = nameList.SelectedName;

    public event EventHandler CanExecuteChanged
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }

For this command we will pass a NameList object, as before. If an item from the list of names has been selected by the user, the SelectedName property will not be null, so we check this in CanExecute to determine if the command should be available. The Execute method extracts the selected name and removes it from the Names collection.

Add a new field for the command to the NameList class:

RemoveCommand _removeNameCommand = new RemoveCommand();

Now create a property in NameList to surface the command for binding:

public RemoveCommand RemoveNameCommand
    get { return _removeNameCommand; }

Finally, update the XAML of the Remove button to bind the command and configure the command parameter to pass the data context reference.

<Button Command="{Binding RemoveNameCommand}" CommandParameter="{Binding .}">Remove</Button>

Run the program to see the results. You should now be able to add names to the list and remove them. The Remove button will only be enabled when a name is selected in the list box.

14 June 2015