"Esc"如何显示?在WPF窗口中处理密钥? [英] How is "Esc" key handled in WPF Window?

查看:118
本文介绍了"Esc"如何显示?在WPF窗口中处理密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如果您可以使用C#提供解决方案,那就太好了.

解决方案

您应该只使用KeyDown事件而不是PreviewKeyDown事件.如果Window的任何子级处理该事件,则不会将其冒泡到Window(从Window向下的PreviewKeyDown隧道),因此不会调用事件处理程序.

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.

解决方案

You should just use the KeyDown event instead of the PreviewKeyDown event. If any child of the Window handles the event, it won't be bubbled up to the Window (PreviewKeyDown tunnels from the Window down), and therefore your event handler won't be called.

这篇关于"Esc"如何显示?在WPF窗口中处理密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆