How do we prevent underscore being used as a control key indicator?

315 Views Asked by At

I am trying to add a menuitem, like this:

Items.Add(new MenuItem()
{
    Header = var_from_a_loop;
});

The var_from_a_loop has some underscores. Say, var_from_a_loop = "A_B_C_D". When run, this becomes "AB_C_D", that is, it removes the first underscore. Now, I know the underscore is treated like a shortcut key indicator (like the above would mean using shortcut Ctrl + B), but I want to disable this. I could probably manage showing the entire string by doing this:

Header = "_" + var_from_a_loop

But I am looking for a better solution, as the above is kind of 'hacky'.

1

There are 1 best solutions below

0
On

If you would use XAML you can get this to work by using this template:

<ContextMenu x:Key="ContextMenu">
    <MenuItem>
        <MenuItem.Header>
            <TextBlock>_Some text here</TextBlock>
        </MenuItem.Header>
    </MenuItem>
</ContextMenu>  

This then displays the item with underscore included. If you use a Label instead of the TextBlock it will be evaluated as the shortcut key.
Just for the sake of the example one would use said ContextMenu using a Style. Say we are adding context menu to a ListView items:

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
</Style>