How do I disable Mnemonics in a WPF MenuItem?

心不动则不痛 提交于 2019-12-05 04:55:16
Omer Raviv

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!