Reputation: 1266
I am using the following tag in my xaml
to bind the enter key to a command.
<KeyBinding Command="{Binding EnterKeyCommand}" Key="Enter" />
But if i press the enter key 5 times (very quickly) the command is called 5 times. How can i prevent this?
Upvotes: 0
Views: 1031
Reputation: 827
If you wanted to add a delay between the Command executing for a first time and it being able to be executed again, you can just set canExecute to false for a period of time:
public class EnterKeyCommand : ICommand
{
private bool canExecute;
public EnterKeyCommand()
{
this.canExecute = true;
}
public bool CanExecute(object parameter)
{
return this.canExecute;
}
public void Execute(object parameter)
{
this.canExecute = false;
Debug.WriteLine("Running Command");
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += (sender, args) =>
{
this.canExecute = true;
timer.Stop();
};
timer.Start();
}
public event EventHandler CanExecuteChanged;
}
Upvotes: 2
Reputation: 13224
Assuming that EnterKeyCommand
is an ICommand
, set its ICommand.CanExecute
to false
when it is invoked, and back to true
when it is ok to execute it again (raising ICommand.CanExecuteChanged
both times).
Upvotes: 2