WPF TextBox MenuItem loses focus when moving the mouse

In my WPF application, I want a menu item to have a text box. I managed to do this using the following code:

<Menu Height="23" HorizontalAlignment="Stretch" Name="MainMenu" VerticalAlignment="Top"> <MenuItem Header="File"> <MenuItem Header="Exit" Click="menuItemExit_Click" /> </MenuItem> <MenuItem Header="Settings"> <MenuItem Header="Some setting" IsCheckable="True" /> <Separator /> <MenuItem> <MenuItem.Header> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Label Content="Some value:" Margin="0,3,6,0" Padding="0" /> <TextBox Margin="0,0,0,6" Grid.Column="1" /> </Grid> </MenuItem.Header> </MenuItem> </MenuItem> </Menu> 

This code displays the menu item as I expected, but if I start to enter some value in the text field, and then move the mouse (without clicking) away from the menu item of the text field, the text field loses focus and I can’t continue to enter text until I click on the text box again. How can I achieve the same behavior as a text field menu item in WinForms? That is, the text field loses focus if the user clicks outside the text field or presses the tab key.

Thanks in advance.

+7
source share
3 answers

As I wrote, I'm not sure how you use your menu control. But maybe this piece of code can help you or give you a hint:

 <TextBox Margin="0,0,0,6" Grid.Column="1" PreviewLostKeyboardFocus="OnPreviewLostKeyboardFocus"/> 

and the corresponding method:

 private void OnPreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { if (MainMenu.IsKeyboardFocusWithin) { e.Handled = true; } } 
+5
source

I know this answer is probably too late to help you, but perhaps it will help anyone who is looking for a fix for this problem.

Setting Focusable=false in MenuItems also works. It still allows them to click and allows focused controls. However, it disables the ability to navigate menus using the keyboard, presenting an accessibility problem.

The accessibility problem can be solved with a little creativity, however, if each menu item is a custom item. For example:

 <MenuItem Focusable="False"> <MenuItem.Header> <StackPanel Orientation="Horizontal" Focusable="True" FocusVisualStyle="{x:Null}"> <TextBlock Text="Do something!" /> </StackPanel> </MenuItem.Header> </MenuItem> 

The code FocusVisualStyle="{x:Null}" needed to hide the dotted focus that would otherwise appear (and looks out of place in the menu).

+1
source

Perhaps this helps:

  <MenuItem StaysOpenOnClick="True"> <MenuItem.Header> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Label Content="Some value:" Margin="0,3,6,0" Padding="0" /> <TextBox Margin="0,0,0,6" Grid.Column="1" /> </Grid> </MenuItem.Header> </MenuItem> 
0
source

All Articles