问题
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?
回答1:
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();
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/19769398/how-do-i-disable-mnemonics-in-a-wpf-menuitem