The RelayCommand<T>
is similar to the RelayCommand
, but allows to directly pass an object to the command. It implements the ICommand
interface and can therefore be used to bind to Command
s in XAML (e.g. as the Command
property of the Button
element). You can then use the CommandParameter
property to pass the object to the command.
XAML example:
<Button Command="{Binding MyCommand}" CommandParameter="{Binding MyModel}" />
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<string,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 RelayCommand<string> MyCommand => new RelayCommand<string>(
obj =>
{
//execute action
Message = obj;
},
obj =>
{
//return true if button should be enabled or not
return obj != "allowed";
}
);
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