How do I disable Mnemonics in a WPF MenuItem?

喜欢而已 提交于 2019-12-22 04:39:15

问题


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

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