Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focusable Panel in WPF

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?

like image 967
Mart Avatar asked Nov 12 '09 11:11

Mart


People also ask

What is focusable in WPF?

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.

What does keyboard focusable mean?

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.

What is focus method in c#?

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.


2 Answers

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

like image 161
Mart Avatar answered Oct 04 '22 21:10

Mart


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.

like image 38
Yogesh Avatar answered Oct 04 '22 20:10

Yogesh