-
-
Notifications
You must be signed in to change notification settings - Fork 4
β‘ Commands
Marc Rousavy edited this page Aug 23, 2018
·
11 revisions
The RelayCommand
is an ICommand
implementation.
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
}
}
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 CommandParameter
s of type T
:
// ...
LoginCommand = new RelayCommand<string>(LoginAction);
// ...
void LoginAction(string parameter)
{
// Login button clicked
}
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 theCanExecute
function