簡體   English   中英

按鍵綁定WPF MVMVM

[英]Key binding wpf mvvm

我在xaml使用以下標記將Enter鍵綁定到命令。

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

但是,如果我按Enter鍵5次(非常快),該命令將被調用5次。 我該如何預防呢?

假設EnterKeyCommandICommand ,則在調用它時將其ICommand.CanExecute設置為false ,並在可以再次執行時將其設置為true (兩次都提高ICommand.CanExecuteChanged )。

如果要在第一次執行命令與再次執行命令之間增加延遲,可以將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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM