当用户单击“转义”按钮时,我希望关闭wpf项目中的窗口。我不想在每个窗口中编写代码,而是希望创建一个类,当用户按转义键时,这个类可以捕获。
发布于 2011-10-07 20:57:37
选项1
使用Button.IsCancel属性。
<Button Name="btnCancel" IsCancel="true" Click="OnClickCancel">Cancel</Button>
当您将按钮的IsCancel属性设置为true时,将创建一个在AccessKeyManager中注册的按钮。然后,当用户按ESC键时,该按钮被激活。
但是,这只适用于对话框。
Option2
如果要关闭Esc按下的窗口,可以向窗口上的PreviewKeyDown添加处理程序。
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
}
private void HandleEsc(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
}
发布于 2020-07-22 06:11:57
这里是一个没有按钮的解决方案,是干净的,更多的MVVM。在对话框/窗口中添加以下XAML:
<Window.InputBindings>
<KeyBinding Command="ApplicationCommands.Close" Key="Esc" />
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandBinding_Executed" />
</Window.CommandBindings>
并在代码隐藏中处理事件:
private void CloseCommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
if (MessageBox.Show("Close?", "Close", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
this.Close();
}
发布于 2020-03-12 00:47:21
在InitializeComponent()后面放一行:
PreviewKeyDown += (s,e) => { if (e.Key == Key.Escape) Close() ;};
请注意,这种代码不会破坏MVVM模式,因为这与UI相关,并且您不访问任何视图模型数据。另一种方法是使用附加属性,这将需要更多的代码。
https://stackoverflow.com/questions/7691713
复制相似问题