2016-06-28 52 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