I have written myself a SingleExecutionCommand (I’m not sure about that name yet. Feel free to suggest an other, but that’s not my question), which doesn’t allow a button to be pressed again before the first execution is finished. Well, at least that’s the plan.
I want to use the CommandManager
to handle my CanExecuteChanged-Event, but I also need to trigger this event on my own whenever I change my ExecutionIsRunning
-Flag.
This is the Code of my Command:
public class SingleExecutionCommand<T> : DelegateCommand<T>
{
protected readonly Func<T, Task> AwaitableExecuteDelegate;
public bool ExecutionIsRunning { get; protected set; }
public SingleExecutionCommand(Func<T, Task> awaitableExecute, Predicate<T> canExecute = null) :
base(null, canExecute)
{
AwaitableExecuteDelegate = awaitableExecute;
}
public SingleExecutionCommand(Action<T> execute, Predicate<T> canExecute = null)
: base(execute, canExecute)
{
AwaitableExecuteDelegate = null;
}
public async override void Execute(object parameter)
{
if (parameter != null && !(parameter is T)) throw new ArgumentException("Command Parameter has the wrong type.");
if (AwaitableExecuteDelegate == null)
{
ExecutionIsRunning = true;
base.Execute(parameter);
ExecutionIsRunning = false;
}
else
{
ExecutionIsRunning = true;
await AwaitableExecuteDelegate((T)parameter);
ExecutionIsRunning = false;
}
}
public override bool CanExecute(object parameter)
{
return (!ExecutionIsRunning) && base.CanExecute(parameter);
}
}
If tried to do this in my DelegateCommand<T>
-Class:
protected void FireCanExcuteChangedEvent()
{
if (CanExecuteChanged == null) return;
CanExecuteChanged(this, EventArgs.Empty);
}
but that doesn’t work, because that event is a rerouted event (to the CommandManager.RequerySuggested
) and not a real event. So, how can I use both, the CommandManager
and my own event?
Edit:
The CanExecuteChanged
-event looks like this:
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}