2009-11-06 55 views
1

我有一個WPF窗口,其中包含一個名爲Cancel的按鈕。在一般情況下,我希望用戶能夠按Alt + C取消他們的操作並關閉程序。因此,按鈕標題爲「_Cancel」。WPF熱鍵無需修改器觸發

問題1:在Window_Load期間,如果我按C不帶修飾符,則Cancel_Clicked事件觸發,程序關閉。

問題2:我的程序打開後,假設我沒有與窗口上的任何內容交互,按C鍵不加修飾符將關閉程序。

請注意,由於問題2,使用某種布爾值來跟蹤「已加載」狀態將不起作用。

我在做什麼錯?有任何想法嗎?

回答

2

你最好的解決辦法是重構爲一個command:

<Window.CommandBindings> 
    <CommandBinding Command="Cancel" Executed="CancelExecuted" /> 
</Window.CommandBindings> 

<Window.InputBindings> 
    <KeyBinding Command="Cancel" Key="C" Modifiers="Alt"/> 
</Window.InputBindings> 
1

我發現,這是相同的行爲是的WinForms。 (我一直懷疑,直到我創建了一個測試項目來試用它!)。這是以前的一個SO問題,它與同樣的場景有關:WPF Accelerator Keys like Visual Studio

如果您想強制使用Alt修改器觸發ALKE,您可以考慮將操作重構爲命令。

這是一個非常快速和黑客的演示,瞭解如何執行這樣的命令。

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     this.InputBindings.Add(new KeyBinding(new DoActionCommand(() => DoIt()), new KeyGesture(Key.C, ModifierKeys.Alt))); 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     DoIt(); 
    } 

    private void DoIt() 
    { 
     MessageBox.Show("Did It!"); 
    } 

} 

public class DoActionCommand : ICommand 
{ 
    private Action _executeAction; 

    public DoActionCommand(Action executeAction) 
    { 
     _executeAction = executeAction; 
    } 
    #region ICommand Members 

    public bool CanExecute(object parameter) 
    { 
     return true; 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     if (_executeAction != null) 
     { 
      _executeAction.Invoke(); 
     } 
    } 

    #endregion 
}