如何在 WPF 页面或 UserControl 对象上捕获 KeyDown 事件? [英] How can I capture KeyDown event on a WPF Page or UserControl object?

查看:42
本文介绍了如何在 WPF 页面或 UserControl 对象上捕获 KeyDown 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 UserControl 的页面.如果用户在我想要处理的页面上的任何地方按下 Esc.

I have a Page with a UserControl on it. If the user presses Esc while anywhere on Page I want to handle.

我认为这就像连接 PreviewKeyDown 事件,测试 Esc 键,然后处理它一样简单.但是,当我在事件处理程序中放置断点时,我发现它从未被调用.我想也许 UserControl 可能会被击中,所以我在那里尝试了 PreviewKeyDown...同样的结果.

I thought this would be as easy as hooking up the PreviewKeyDown event, testing for the Esc key, and then handling it. However, when I placed I breakpoint in the event handler I found it was never getting called. I thought perhaps the UserControl might be getting hit, so I tried PreviewKeyDown there... same result.

有谁知道在 Page 对象上测试 KeyDown 或 PreviewKeyDown 的正确位置吗?

Does anyone know the proper place to test for a KeyDown or PreviewKeyDown on a Page object?

推荐答案

我相信 PreviewKeyDown 事件是一个隧道路由事件,而不是冒泡事件.如果是这种情况,那么如果您的 Page 没有收到该事件,则 UserControl 也不应如此,因为它位于可视化树中的 Page 下方.也许尝试在您的应用程序的顶层(也许是窗口?)处理它,看看它是否正在获取事件?

I believe that the PreviewKeyDown event is a tunneling routed event, rather than a bubbling one. If that is the case, then if your Page isn't getting the event, the UserControl shouldn't be either since it is below the Page in the visual tree. Maybe try handling it at the top level of your app (Window perhaps?) and see if it is getting the event?

另一个可能有帮助的选项是使用类似 CodePlex Snoop 之类的东西来找出事件的位置去.

Another option that might help would be to use something like Snoop in CodePlex to figure out where the events are going.

这篇关于如何在 WPF 页面或 UserControl 对象上捕获 KeyDown 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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