Skip to content

Commands

Niclas Kristek edited this page Aug 5, 2019 · 9 revisions

The ViewModelCommand<T> and AsyncViewModelCommand<T> abstract classes provide base implementations for ICommand and IAsyncCommand respectively. They implement a Context property which is used as a context for the CanExecute, Execute and ExecuteAsync methods.

The virtual OnContextPropertyChanging and OnContextPropertyChanged methods are automatically reattached every time the Context 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.

public class MyCommand
    : ViewModelCommand<MyViewModel>
{
    protected override void OnContextPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e == null || String.IsNullOrEmpty(e.PropertyName) 
        || e.PropertyName.Equals(nameof(MyViewModel.MyProperty)))
            NotifyCanExecuteChanged();
    }

    protected override bool CanExecute(MyViewModel viewModel, object parameter)
    {
        return viewModel.MyProperty > 0;
    }

    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.

Clone this wiki locally