【问题标题】:CommandBindings shortcuts executing twiceCommandBindings 快捷方式执行两次
【发布时间】:2016-06-28 15:59:04
【问题描述】:

这就是我在我的 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,对话框会显示两次。

为什么会这样?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    查看MSDNthis SO post,我可以提出两个选项来说明您为什么要参加两次活动。要确定,请为事物添加事件处理程序,然后查看调用了哪些事件处理程序。

    1. 正在为 PreviewCanExecuteCanExecute 事件调用它
    2. 当对象获得键盘焦点和释放鼠标时调用它

    但是,您错误地使用了CanExecuteCanExecute 应该只返回 truefalse。用户应该不知道它正在被调用。我见过的一种有助于实现这一点的用途是用于菜单。如果你给它一个绑定,它不能执行,菜单项会变灰。

    因此,如果用户无论如何都可以点击它,那么您应该在Executed 方法中使用MessageBox,而不是CanExecute 方法。

    【讨论】:

    • afaik,只要将属性 CanExecuteRoutedEventArgs#CanExecute 设置为 true 或 false,CanExecuted 内部是否有任何逻辑都没有关系。我知道我可能没有正确使用它(在设计方面),但这并不能证明为什么要执行两次。
    • 查看编辑。我能找到几个原因,但看起来你必须通过实验才能确定。
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 2019-07-10
    • 2016-08-14
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    相关资源
    最近更新 更多