I need to make a Panel focusable in WPF, so that it captures keyboard events just as any other focusable control:
KeyDown
or KeyUp
event is raised at panel levelI experimented FocusManager.IsFocusScope="True"
on the Panel and myPanel.Focus()
returns true
but the Panel KeyUp event handler still isn't called.
Am I missing something?
The Focusable property for a control indicates whether the control can receive focus, which means that the control can receive keyboard input after the user clicks on the control. Focusable is normally set to true for controls that are designed to accept user input.
When an HTML element is able to handle keyboard input, it is said to have focus. Exactly one element is able to have focus in a time. In most browsers, users can move focus by pressing the Tab key and the Shift + Tab keys.
The Focus method attempts to give the specified element keyboard focus. The returned element is the element that has keyboard focus, which might be a different element than requested if either the old or new focus object block the request.
After more investigation, the Panel has the keyboard focus and keeps it until an arrow key or TAB is pressed (which starts the focus cycling).
I just added a handler for the KeyDown
event with `e.Handled = true;' and now everything works correctly.
To sum it up, to have a focusable Panel:
FocusManager.IsFocusScope="True"
to the PanelmyPanel.KeyDown += new KeyEventHandler( delegate(object sender, KeyEventArgs e) { if (e.Key == Key.Left || e.Key == Key.Up || e.Key == Key.Right || e.Key == Key.Down || e.Key == Key.Tab) e.Handled = true; } );
Finally give it the focus with myPanel.Focus();
.
If your panel does not contain any child elements, even using FocusManager.IsFocusScope="True"
will not fire the GotFocus event. Panel are not designed to take keyboard input or focus. Instead, most of the times (like if the child element is a Button control) FocusManager.IsFocusScope="True"
will even eat up the KeyUp/KeyDown events. The event will not be fired for neither your control nor your panel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With