如何在转义键上关闭WPF中的窗口

Kis*_*mar 39 .net c# wpf c#-4.0

可能重复:
如何为项目中的所有WPF窗口分配"关闭按键时按键"行为?

我想在用户单击转义按钮时关闭我的wpf项目中的窗口.我不想在每个窗口中编写代码,但是想要创建一个可以捕获用户按下转义键的类.

Cha*_*thJ 126

选项1

使用Button.IsCancel属性.

<Button Name="btnCancel" IsCancel="true" Click="OnClickCancel">Cancel</Button>
Run Code Online (Sandbox Code Playgroud)

将按钮的IsCancel属性设置为true时,将创建一个使用AccessKeyManager注册的Button.然后,当用户按下ESC键时,该按钮被激活.

但是,这仅适用于Dialogs.

选项2

如果要在Esc按下关闭窗口,可以在窗口上为PreviewKeyDown添加处理程序.

public MainWindow()
{
    InitializeComponent();

    this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
}

private void HandleEsc(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape)
        Close();
}
Run Code Online (Sandbox Code Playgroud)

  • 我不想使用按钮……谢谢,我找到了解决方案 (2认同)
  • @kishorejangid - 你能在这里发表你的答案吗? (2认同)
  • 如果你发现解决方案正确,请投票 (2认同)

dot*_*NET 9

这是一个干净且更像 MVVM 的无按钮解决方案。将以下 XAML 添加到您的对话框/窗口中:

<Window.InputBindings>
  <KeyBinding Command="ApplicationCommands.Close" Key="Esc" />
</Window.InputBindings>

<Window.CommandBindings>
  <CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandBinding_Executed" />
</Window.CommandBindings>
Run Code Online (Sandbox Code Playgroud)

并在代码隐藏中处理事件:

private void CloseCommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
  if (MessageBox.Show("Close?", "Close", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
    this.Close();
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*icu 6

在 InitializeComponent() 之后放置一行:

 PreviewKeyDown += (s,e) => { if (e.Key == Key.Escape) Close() ;};
Run Code Online (Sandbox Code Playgroud)

请注意,这种隐藏的代码不会破坏 MVVM 模式,因为这是与 UI 相关的,并且您无法访问任何视图模型数据。另一种方法是使用需要更多代码的附加属性。