-
Notifications
You must be signed in to change notification settings - Fork 6
Commands
The ViewModelCommand<T>
and AsyncViewModelCommand<T>
abstract classes provide base implementations for ICommand
and IAsyncCommand
respectively. They implement a Parent
property which is used as a context for the CanExecute
, Execute
and ExecuteAsync
methods. The virtual OnParentPropertyChanging
and OnParentPropertyChanged
methods are automatically reattached every time the Parent
property changes. They can be used to raise events on the CanExecuteChanged
event handler, if a specific property changes which is used in the CanExecute
method. Please note, that a null or empty value of the property name indicates, that all properties should be reevaluated.
A basic example of a ViewModelCommand<T>
:
public class TestCommand
: ViewModelCommand<MyViewModel>
{
protected override bool CanExecute(MyViewModel viewModel, object parameter)
{
return viewModel.MyProperty > 0;
}
protected override void OnParentPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e == null || String.IsNullOrEmpty(e.PropertyName)
|| e.PropertyName.Equals(nameof(MyViewModel.MyProperty)))
NotifyCanExecuteChanged();
}
protected override void Execute(MyViewModel viewModel, object parameter)
{
// execute...
}
}
The AsyncViewModelCommand<T>
class implements a virtual AllowsConcurrentExecution
property which defaults to false. If concurrent execution is allowed, override the property accordingly. An internal thread safe counter is used to determine, if any execution is running to correctly evaluate the state of the IsWorking
property.