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?
This is tested and defintiely works.
PreviewKeyDown is what most people miss. Think of PreviewKeyDown as an overall observer of keyboard events, (but cannot effect them if im not mistaken) and KeyDown evens are being listened to within the confines of the control or class you are currently in.
I had a similar issue when calling the WPF window out of WinForms. Neither KeyDown or PreviewKeyDown events were fired.
However, showing window as a dialog, it worked
PreviewKeyDown event fired like a charm for Escape and Arrow keys.
Hope this works.
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?
Another option that might help would be to use something like Snoop in CodePlex to figure out where the events are going.
What exactly worked for me:
Only on window Loaded event listen to PreviewKeyDown event:
Attach to the Window's Event
After the control is loaded, attach to the Window's
KeyDown
event (or any event) by usingWindow.GetWindow(this)
, like so:The XAML
The Code Behind
I propose a method which strengthens the one @Doc mentioned.
The following code @Doc mentioned will work since the KeyDown routed event is bubbled to the outermost
Window
. OnceWindow
receives the KeyDown event bubbled from an inner element,Window
triggers any KeyDown event-handler registered to it, like thisHandleKeyPress
.But this
+=
is risky, a programmer is more likely to forget to un-register the event-handler. Then memory leaking or some bugs will happen.Here I suggest,
YourWindow.xaml.cs
YourUserControlViewModel.cs or YourUserControl.xaml.cs
There is no need to code in xaml.