Elentok's Blog

About me

Keyboard Friendly WPF Popup Control

A couple of weeks ago I talked about various tips for building more keyboard friendly WPF application, now I will I am going to focus about the WPF Popup control.

To make the popup control more keyboard friendly we need to make the following changes:

  1. When the popup opens, the keyboard focus should move to the contents of the popup.
  2. Lock the keyboard focus inside the popup until it closes.

To do this, I created the "FriendlyPopup" control (or "EnhancedPopup" or whatever):

public class FriendlyPopup : Popup
  {
    protected override void OnOpened(EventArgs e)
    {
      base.OnOpened(e);

      // move the focus into the popup when it opens.
      this.Child.MoveFocus(new TraversalRequest(
        FocusNavigationDirection.Next));
    }

    protected override void OnLostKeyboardFocus(
      KeyboardFocusChangedEventArgs e)
    {
      base.OnLostKeyboardFocus(e);

      // if the focus is still inside the popup, 
      // don't do anything.
      if (this.IsKeyboardFocusWithin)
        return;

      // if the popup is still open, keep the focus inside.
      if (this.IsOpen)
        this.Child.MoveFocus(new TraversalRequest(
          FocusNavigationDirection.Next));
    }
  }
Next:WPF and KeyboardNavigation TabNavigation = "Local"