我在xaml
中使用以下标记将enter键绑定到命令。
<KeyBinding Command="{Binding EnterKeyCommand}" Key="Enter" />
但如果我按下回车键5次(非常快),则命令被调用5次。我该如何防止这种情况?
答案 0 :(得分:2)
假设EnterKeyCommand
是ICommand
,请在调用时将ICommand.CanExecute
设置为false
,并在可以执行时将其设置回true
它再次(两次提升ICommand.CanExecuteChanged
)。
答案 1 :(得分:2)
如果你想在第一次执行命令和再次执行命令之间添加一个延迟,你可以在一段时间内将canExecute设置为false:
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;
}