1
votes

I have a Textbox withing the ControlTemplate of a MenuItem, which is inside a ContextMenu. The Textbox works well and I can type in it properly. But if I move the mouse over any of the other menu items in the context menu, they claim focus and I lose focus from the textbox. At this point I have to click back into the textbox to continue typing.

Is there a pattern or accepted method of resolving this issue?

Thanks

2
Could you please post some code? I have tried your implementation and I don't have this problem - MaRuf
We have restyled the menu items significantly, so its kind of hard to demo here. If you're not seeing an issue, maybe its because of our styling. - Dean

2 Answers

0
votes

If you want to take back focus, you can type as below.

textBox.CaptureMouse();
textBox.ReleaseMouseCapture();

I think it can catch focus to textbox.

0
votes

Well after trying a few different things, I got something to work:

For all other menu items that can capture focus (on mouse enter), set e.Handled = true for the PriviewGoTKeyboardFocus event:

void menuItem_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
  e.Handled = true;
}

One can do this automatically from a window base class by looping through all menu items in a context menu. This requires hijacking the tag for those menuitems in which you insert the textbox.

void contextMenu_Opened(object sender, RoutedEventArgs e)

{
  ContextMenu contextMenu = sender as ContextMenu;
  foreach (FrameworkElement frameworkElement in contextMenu.Items)
  {
    if (frameworkElement is MenuItem)
    {
      MenuItem menuItem = (frameworkElement as MenuItem);
      if (!(menuItem.Tag != null && menuItem.Tag.ToString() == "MaintainFocus"))
        menuItem.PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(menuItem_PreviewGotKeyboardFocus);
    }
  }
}
void contextMenu_Closed(object sender, RoutedEventArgs e)
{
  ContextMenu contextMenu = sender as ContextMenu;
  foreach (FrameworkElement frameworkElement in contextMenu.Items)
  {
    if (frameworkElement is MenuItem)
    {
      MenuItem menuItem = (frameworkElement as MenuItem);
      if (!(menuItem.Tag != null && menuItem.Tag.ToString() == "MaintainFocus"))
        menuItem.PreviewGotKeyboardFocus -= menuItem_PreviewGotKeyboardFocus;
    }
  }
}