The page has been moved to GitHub

RelayCommand

Package: MyToolkit (PCL)
Platforms: All (PCL)

Inherits from CommandBase
See also AsyncRelayCommand

The RelayCommand class implements the interface ICommand which can be used in various XAML elements, for example the Button control. The following listing shows sample XAML which binds to commands:

<Button Command={Binding DoItCommand}" />
<Button Command={Binding DeletePersonCommand}" CommandParameter="{Binding Person}" />

And the view model with the commands:

public MyViewModel
{
    public ICommand DoItCommand { get; private set; }
    public ICommand DeletePersonCommand { get; private set; }

    public MyViewModel()
    {
        DoItCommand = new RelayCommand(DoIt);
        DeletePersonCommand = new RelayCommand<Person>(
            DeletePerson, person => person != null);
    }
	
    public void DoIt()
    {
        // your code here
    }
	
    public void DeletePerson(Person person)
    {
        // your code here
    }
}

The RelayCommand without parameter (non-generic) also implements INotifyPropertyChanged for the CanExecute property.

To manually tell the GUI that the can execute state has changed, simply call the RaiseCanExecuteChanged method:

DeletePersonCommand.RaiseCanExecuteChanged();

Last edited Jun 3, 2015 at 9:54 PM by rsuter, version 15