键绑定wpf mvvm

时间:2015-03-23 21:56:55

标签: c# wpf xaml mvvm

我在xaml中使用以下标记将enter键绑定到命令。

<KeyBinding Command="{Binding EnterKeyCommand}" Key="Enter" />

但如果我按下回车键5次(非常快),则命令被调用5次。我该如何防止这种情况?

2 个答案:

答案 0 :(得分:2)

假设EnterKeyCommandICommand,请在调用时将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;
}