Skip to content

⚑ Commands

Marc Rousavy edited this page Aug 23, 2018 · 11 revisions

The RelayCommand is an ICommand implementation.

RelayCommand

For example, a button's Command property can bind to an ICommand:

<Window ...>
    <Button Command="{Binding LoginCommand}" />
</Window>

Initialize the ICommand with a non-generic RelayCommand instance and the given action/callback:

class LoginViewModel : ViewModel
{
    private ICommand _loginCommand;
    public ICommand LoginCommand
    {
        get => _loginCommand;
        set => Set(ref _loginCommand, value);
    }

    public LoginViewModel()
    {
        LoginCommand = new RelayCommand(LoginAction);
    }

    void LoginAction(object parameter)
    {
        // Login button clicked
    }
}

Parameterized

Next to the Command binding, most controls also support supplying additional command parameters:

<Window ...>
    <Button Command="{Binding LoginCommand}" CommandParameter="{Binding Text, ElementName=UsernameTextBox}" />
</Window>

Initialize as RelayCommand<T> to only allow CommandParameters of type T:

// ...
LoginCommand = new RelayCommand<string>(LoginAction);
// ...
void LoginAction(string parameter)
{
    // Login button clicked
}

CanExecute

You can also define a custom query (CanExecute) to check whether the command is currently able to execute. This requires the parameterized command, as it uses the parameter to check for validity. The WPF Button, for example, gets disabled if CanExecute evaluates to false.

// ...
LoginCommand = new RelayCommand<string>(LoginAction, CanLogin);  // or use a lambda
// ...
bool CanLogin(string parameter)
{
    return !string.IsNullOrWhitespace(parameter);
}

CanExecuteChanged will automatically be called when a property changes in the CanExecute function