Skip to content

Instantly share code, notes, and snippets.

@mr5z

mr5z/BaseCommand.cs

Created Jan 13, 2021
Embed
What would you like to do?
DelegateCommand wrapper
public class BaseCommand : DelegateCommand
{
public double InvocationDelayInSeconds { get; set; }
private DateTime lastInvokeTime = DateTime.MinValue;
private readonly Func<bool> canExecute;
public BaseCommand(
Action executeAction,
double invocationDelayInSeconds = 1)
: base(executeAction)
{
InvocationDelayInSeconds = invocationDelayInSeconds;
}
public BaseCommand(
Action executeAction,
Func<bool> canExecute,
double invocationDelayInSeconds = 1)
: base(executeAction, canExecute)
{
this.canExecute = canExecute;
InvocationDelayInSeconds = invocationDelayInSeconds;
}
protected override void Execute(object parameter)
{
if (DateTime.Now - lastInvokeTime < TimeSpan.FromSeconds(InvocationDelayInSeconds))
return;
if (IsActive || (canExecute != null && !canExecute()))
return;
IsActive = true;
base.Execute(parameter);
IsActive = false;
lastInvokeTime = DateTime.Now;
}
protected override void OnIsActiveChanged()
{
base.OnIsActiveChanged();
RaiseCanExecuteChanged();
}
protected override bool CanExecute(object parameter)
{
return !IsActive;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment