In my WPF application I want a menu item to have a text box. I have 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 like I expected but if I start typing some value into the text box and then move the mouse (not clicking) away from the text box menu item, the text box loses focus and I cannot continue typing until I click on the text box again. How can I achieve the same behaviour as a text box menu item in WinForms? That is, the text box only loses focus if the user clicks outside the text box or hits the tab key.
Thanks in advance.
As I wrote I am not sure how you use your menu control. But maybe this code snipped can help you or give you a hint:
<TextBox Margin="0,0,0,6" Grid.Column="1" PreviewLostKeyboardFocus="OnPreviewLostKeyboardFocus"/>
and the according method:
private void OnPreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (MainMenu.IsKeyboardFocusWithin)
{
e.Handled = true;
}
}
I know this answer is probably way too late to help you, but maybe it'll help anyone searching for fixes to this issue.
Setting Focusable=false
on the MenuItems also works. It still allows them to be clicked and allows their contained controls to have focus. However, it disables the ability to navigate the menu using just the keyboard, introducing an accessibility issue.
The accessibility issue can be solved with a little creativity, however, by giving every menu item a focusable element. For example:
<MenuItem Focusable="False">
<MenuItem.Header>
<StackPanel Orientation="Horizontal" Focusable="True" FocusVisualStyle="{x:Null}">
<TextBlock Text="Do something!" />
</StackPanel>
</MenuItem.Header>
</MenuItem>
The FocusVisualStyle="{x:Null}"
code is required to hide the dotted focus that would otherwise appear (and looks out of place in a menu).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With