I need to make a Panel focusable in WPF, so that it captures keyboard events just as any other focusable control:
- The user clicks inside the Panel to give it focus
- any
KeyDown
orKeyUp
event is raised at panel level - if another focusable element outside the panel is clicked, the panel loses focus
I experimented FocusManager.IsFocusScope="True"
on the Panel and 开发者_JS百科myPanel.Focus()
returns true
but the Panel KeyUp event handler still isn't called.
Am I missing something?
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:
- add
FocusManager.IsFocusScope="True"
to the Panel - prevent from loosing focus on arrows and Tab key with:
myPanel.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.
精彩评论