2010-04-19 30 views
5

我想要退出鍵來關閉我的WPF窗口。但是,如果有一個可以使用Escape鍵的控件,我不想關閉該窗口。當按下ESC鍵時,關於如何關閉WPF窗口有多種解決方案。例如。 How does the WPF Button.IsCancel property work?在WPF窗口中如何處理「Esc」鍵?

但是,此解決方案關閉窗口,而不考慮是否存在能夠使用退出鍵的活動控件。

例如,我有一個DataGrid窗口。 dataGrid上的一列是組合框。如果我正在更改組合框,並點擊Escape,則控件應該從編輯組合框(正常行爲)開始。如果我現在再次擊中Escape,那麼窗口應該關閉。我想要一個通用的解決方案,而不是寫很多自定義代碼。

如果您可以在C#中提供解決方案,那將非常棒。

回答

3

你應該只使用,而不是PreviewKeyDown事件KeyDown事件。如果Window的任何孩子處理該事件,它將不會冒泡到該窗口(PreviewKeyDown隧道從Window向下),因此您的事件處理程序將不會被調用。

+0

這適用於我。但並非在所有情況下。特別是,我正在使用Telerik的DataGrid控件。如果一個單元格有一個組合框,並且它已展開,然後我點擊Escape,則Escape鍵不會傳播到窗口。但是,如果ComboBox未展開,但處於編輯模式,則Escape鍵會傳播。我認爲這可能是一個控制的錯誤。你的建議確實有效。 – Markus2k 2010-04-21 14:24:02

1

可能有一個更簡單的方法,但你可以用散列碼來完成。 Keys.Escape是另一種選擇,但有時候由於某種原因,我無法讓它工作。您沒有指定一個語言,所以這裏是VB.NET一個例子:

Private Sub someTextField_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles someTextField.KeyPress 

    If e.KeyChar.GetHashCode = 1769499 Then ''this number is the hash code for escape on my computer, do not know if it is the same for all computers though. 
     MsgBox("escape pressed") ''put some logic in here that determines what ever you wanted to know about your "active control" 
    End If 

End Sub 
+0

感謝您的回覆。我感興趣的語言是C#。 我正在尋找這個問題的通用解決方案。我不想爲每個控件指定特定的代碼。 – Markus2k 2010-04-19 03:57:31

1
class Commands 
{ 
    static Command 
    { 
     CloseWindow = NewCommand("Close Window", "CloseWindow", new KeyGesture(Key.Escape)); 
     CloseWindowDefaultBinding = new CommandBinding(CloseWindow, 
      CloseWindowExecute, CloseWindowCanExecute); 
    } 

    public static CommandBinding CloseWindowDefaultBinding { get; private set; } 
    public static RoutedUICommand CloseWindow { get; private set; } 

    static void CloseWindowCanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     e.CanExecute = sender != null && sender is System.Windows.Window; 
     e.Handled = true; 
    } 
    static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e) 
    { 
     ((System.Windows.Window)sender).Close(); 
    } 
} 

// In your window class's constructor. This could also be done 
// as a static resource in the window's XAML resources. 
CommandBindings.Add(Commands.CloseWindowDefaultBinding);