2016-06-28 56 views
1

这是怎么了我已经实现了我的WPF应用程序的快捷方式:化CommandBindings快捷键两次执行

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,则会显示对话框两次。

任何原因为什么发生这种情况?

回答

2

看着MSDN,以及this SO post,有两个选项,我可以与你为什么你得到两次事件。要知道肯定,添加事件处理程序的东西,并看看哪些被调用。

  1. 它被称为为PreviewCanExecuteCanExecute事件
  2. 它被称为当对象接收键盘焦点,当鼠标被释放

但是,你正在使用CanExecute不正确。 CanExecute只应返回truefalse。用户应该不知道它正在被调用。我见过的一个用法是帮助菜单生效。如果您给它一个绑定,并且它不能执行,菜单项将变灰。

因此,如果用户可以单击它,那么你应该在Executed方法中有MessageBox,而不是CanExecute方法。

+1

afaik,只要您将CanExecuteRoutedEventArgs#CanExecute属性设置为true或false,就可以执行CanExecuted中的任何逻辑。我知道我可能没有正确使用它(在设计方面),但这并不能证明为什么执行两次。 – Misters

+0

请参阅编辑。有几个原因我能找到,但看起来你必须试验才能确定。 – David

+1

PreviewCanExecute是答案,谢谢! – Misters