“Esc”如何? WPF 窗口中处理的键?
我想要使用 Escape 键关闭 WPF 窗口。但是,如果有一个控件可以使用该 Escape 键,我不想关闭窗口。关于按下 ESC 键时如何关闭 WPF 窗口有多种解决方案。例如。 WPF Button.IsCancel 属性如何工作?
解决方案关闭窗口,而不考虑是否存在可以使用 Escape 键的活动控件。
例如。我有一个带有 DataGrid 的窗口。 dataGrid 上的列之一是组合框。如果我要更改组合框并按 Escape 键,则控件应该退出组合框的编辑(正常行为)。如果我现在再次按 Esc 键,那么窗口应该关闭。我想要一个通用的解决方案,而不是编写大量自定义代码。
如果你能提供一个 C# 解决方案那就太好了。
I want the Escape key to close my WPF window. However if there is a control that can consume that Escape key, I don't want to close the Window. There are multiple solutions on how to close the WPF Window when ESC key is pressed. eg. How does the WPF Button.IsCancel property work?
However this solution closes the Window, without regard to if there is an active control that can consume the Escape key.
For eg. I have a Window with a DataGrid. One of the columns on the dataGrid is a combobox. If I am changing the ComboBox, and hit Escape, then the control should come out of editing of the comboBox (Normal Behavior). And if I now hit Escape again, then the Window should close. I would like a generic solution, instead of writing a lot of custom code.
If you can provide a solution in C# it would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该只使用
KeyDown
事件而不是PreviewKeyDown
事件。如果Window
的任何子级处理该事件,则该事件不会向上冒泡到 Window(PreviewKeyDown
从Window
向下传输),因此您的事件处理程序将不会被调用。You should just use the
KeyDown
event instead of thePreviewKeyDown
event. If any child of theWindow
handles the event, it won't be bubbled up to the Window (PreviewKeyDown
tunnels from theWindow
down), and therefore your event handler won't be called.可能有更简单的方法,但您可以使用哈希码来完成。 Keys.Escape 是另一种选择,但有时由于某种原因我无法使其工作。您没有指定语言,因此这里是 VB.NET 中的示例:
There may be an easier way, but you could do it with the hash code. Keys.Escape is another option, but sometimes I cannot get that to work for some reason. You didn't specify a language so here is an example in VB.NET: