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)
这是一个干净且更像 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)
在 InitializeComponent() 之后放置一行:
PreviewKeyDown += (s,e) => { if (e.Key == Key.Escape) Close() ;};
Run Code Online (Sandbox Code Playgroud)
请注意,这种隐藏的代码不会破坏 MVVM 模式,因为这是与 UI 相关的,并且您无法访问任何视图模型数据。另一种方法是使用需要更多代码的附加属性。