RelayCommand

Rico Suter edited this page Jun 3, 2015 · 5 revisions
  • 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 CreatePersonCommand}" />
<Button Command="{Binding DeletePersonCommand}" 
        CommandParameter="{Binding Person}" />

And the view model with the commands:

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

    public MyViewModel()
    {
        CreatePerdonCommand = new RelayCommand(CreatePerson);
        DeletePersonCommand = new RelayCommand<Person>(
            DeletePerson, person => person != null);
    }
 
    public void CreatePerson()
    {
        // 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();
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.