Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable Mnemonics in a WPF MenuItem?

Tags:

c#

menuitem

wpf

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?

like image 574
Omer Raviv Avatar asked Nov 04 '13 14:11

Omer Raviv


2 Answers

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();
    }
}
like image 99
Omer Raviv Avatar answered Oct 05 '22 23:10

Omer Raviv


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.

like image 36
Jesse Chisholm Avatar answered Oct 06 '22 01:10

Jesse Chisholm