tags:

views:

392

answers:

2

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 or KeyUp 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 myPanel.Focus() returns true but the Panel KeyUp event handler still isn't called.

Am I missing something?

+1  A: 

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.

Yogesh
That's what I understood, but the question remains: What do I need to make a Panel focusable? I wish to extend it (maybe by deriving it) to give it that feature.
Mart
+2  A: 

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();.

Mart