How can I capture KeyDown event on a WPF Page or U

2019-01-05 03:31发布

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

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.

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

标签: wpf keydown
8条回答
我想做一个坏孩纸
2楼-- · 2019-01-05 04:16

I have/had the same problem. I have a window which hosts a Frame which loads/navigates to various Page's which at their turn contain just 1 UserControl which contains normal Controls/Elements (Labels, Hyperlinks, etc).

what I discovered (after some hours of frustration of course!!!) is that if you do NOT have the focus on one of the Controls/Elements mentioned above the PreviewKeyDown event does NOT fire on the UserControl (stops somewhere at Frame level) but as soon as you put the focus (for instance calling ctrl.Focus() inside the UserCotrol's Loaded event handler) on one of the controls magic happens, it works, the event fires also for the UserControl.

of course thinking of it afterwards this makes enough sense but I am 100% sure this will cacth at least 5 out of 10 people by surprise :) crazy little thing called WPF...

cheers!

查看更多
3楼-- · 2019-01-05 04:18

Setting the Focusable property to true on my UserControl solved the issue for me.

查看更多
登录 后发表回答