命令绑定快捷键执行两次

本文关键字:两次 绑定 快捷键 执行 命令 | 更新日期: 2023-09-27 17:52:57

这就是我如何在我的wpf应用程序中实现快捷方式:

public static class Shortcuts
    {
        static Shortcuts()
        {
            StartScanningCommand = new RoutedCommand();
            StartScanningCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
}
 public readonly static RoutedCommand StartScanningCommand;
}

在我的xaml视图中,我有这个:

<Window.CommandBindings>
        <CommandBinding Command="{x:Static local:Shortcuts.StartScanningCommand}" x:Name="StartScanningCommand" Executed="StartScanningCommand_Executed" CanExecute="StartScanningCommand_CanExecute"/>    
</Window.CommandBindings>

在xaml的类中:

private void StartScanningCommand_Executed(object sender, ExecutedRoutedEventArgs e)
            {
                Scanner.Start();
            }
        private void StartScanningCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = AppCurrent.GetPermissionManager().CanScan();
            if (!e.CanExecute)
            {
                AppCurrent.Broadcasts.ApplicationStatusBroadcast.NotifySubscribers(this, new ApplicationStatusEventArgs("You dont have permission to scan", StatusType.Error));
            }
        }

但是由于某些原因,StartScanningCommand_CanExecute执行了两次。如果我将MessageBox.Show放入方法中,对话框将显示两次。

为什么会发生这种情况?

命令绑定快捷键执行两次

看看MSDN,以及这篇文章,我可以提出两个选项来解释为什么你会得到两次事件。要确定,请为事物添加事件处理程序,并查看调用哪些事件处理程序。

  1. 正在调用PreviewCanExecuteCanExecute事件
  2. 当对象接收到键盘焦点时调用,当鼠标被释放时调用

但是,您使用CanExecute不正确。CanExecute应该只返回truefalse。用户应该不知道它正在被调用。我所见过的一个有助于实现这一点的用法是用于菜单。如果你给它一个绑定,它不能执行,菜单项将会变成灰色。

因此,如果用户可以不顾一切地单击它,那么您应该在Executed方法中使用MessageBox,而不是CanExecute方法。