The RelayCommand
implements the ICommand
interface and can therefore be used to bind to Command
s in XAML (as the Command
property of the Button
element)
The constructor takes two arguments; the first is an Action
which will be executed if ICommand.Execute
is called (e.g. the user clicks on the button), the second one is a Func<bool>
which determines if the action can be executed (defaults to true, called canExecute
in the following paragraph).
the basic structure is as follows:
public ICommand MyCommand => new RelayCommand(
() =>
{
//execute action
Message = "clicked Button";
},
() =>
{
//return true if button should be enabled or not
return true;
}
);
Some notable effects:
canExecute
returns false, the Button
will be disabled for the usercanExecute
will be checked againMyCommand.RaiseCanExecuteChanged();
to force reevaluation of the canExecute
Func