5

我希望 Escape 键关闭我的 WPF 窗口。但是,如果有一个控件可以使用该 Escape 键,我不想关闭窗口。按下 ESC 键时如何关闭 WPF 窗口有多种解决方案。例如。WPF Button.IsCancel 属性如何工作?

但是,此解决方案会关闭窗口,而不考虑是否存在可以使用 Escape 键的活动控件。

例如。我有一个带有 DataGrid 的窗口。dataGrid 上的一列是组合框。如果我要更改 ComboBox,然后点击 Escape,则控件应该退出组合框的编辑(正常行为)。如果我现在再次点击 Escape,那么窗口应该关闭。我想要一个通用的解决方案,而不是编写大量的自定义代码。

如果您可以在 C# 中提供解决方案,那就太好了。

4

3 回答 3

3

您应该只使用KeyDown事件而不是PreviewKeyDown事件。如果处理事件的任何孩子Window,它不会冒泡到窗口(PreviewKeyDown从下往上的隧道Window),因此不会调用您的事件处理程序。

于 2010-04-19T21:43:40.290 回答
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
于 2010-04-19T02:59:58.970 回答
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);
于 2011-08-16T12:38:26.497 回答