I have dynamic strings appear as the MenuItem's header, which sometimes contains '_'. WPF treats the underscores as signs for mnemonics, but I don't want that. How do I disable that?
After trying all the solutions in the thread WPF listbox. Skip underscore symbols in strings, which didn't seem to work on MenuItems, I did this:
public class EscapeMnemonicsStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
return str != null ? str.Replace("_", "__") : value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
An alternate solution is to put your menu text inside a TextBox
with adjusted properties.
If building your MenuItem
in code, the it would look like this:
var menuItem = new MenuItem();
var menuHeader = new Textbox();
menuHeader.Text = "your_text_here";
menuHeader.IsReadOnly = true;
menuHeader.Background = Brushes.Transparent;
menuHeader.BorderThickness = new Thickness(0);
menuItem.Header = menuHeader;
menuItem.ToolTip = "your detailed tooltip here";
menuItem.Click += YourEventHandlerHere;
yourMenu.Items.Add(menuItem);
If your menu is in XAML and it is just the text that is dynamic, it would look like this:
<MenuItem Name="menuDynamic" Click="menuDynamic_Click">
<MenuItem.Header>
<TextBox Name="dynamicMenu"
Text="With_Underscore"
IsReadOnly="True"
Background="Transparent"
BorderThickness="0" />
</MenuItem.Header>
</MenuItem>
Then your code behind could dynamically set dynamicMenu.Text = "what_ever";
when it needed to.
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