Why do MenuItem headers have underscores before them?
Asked Answered
P

2

13

If you're declaring MenuItems, I've always seen their Header properties declared like this:

<MenuItem Header="_Edit">
    <MenuItem Header="_Undo"/>
    <MenuItem Header="_Redo"/>
</MenuItem>

instead of like this:

<MenuItem Header="Edit">
    <MenuItem Header="Undo"/>
    <MenuItem Header="Redo"/>
</MenuItem>

Is there a reason for this or is it just a convention? In the designer it seems to affect nothing whether I have the underscore behind or not.

Picket answered 22/11, 2013 at 17:24 Comment(1)
I'm guessing it's an old convention of using & to indicate the 'activating key' (char get's underscored in menu and can be used with alt-key) , but & doesn't fair well in average text, so they converted it to '_' since it represents the underscore stuff.Westfahl
R
22

Its to designate the keyboard shortcut.

"_Edit" means that CTRL + E will activate that menu item, whereas

"E_dit" means that CTRL + D will work.

Also, the underscored letter will have an underline when in focus to clue the user in to the keyboard shortcut.

From MSDN

Redhead answered 22/11, 2013 at 17:29 Comment(3)
Also: when displayed and in focus, the letter after the underscore is underlined.Chester
This answer is not correct. The character following the underscore is the AccessKey, not the "keyboard shortcut" (aka KeyGesture). The AccessKey is used when opening a menu with the Alt key or pressing the Alt key after opening the menu. Then typing the AccessKey (without Ctrl!) executes the command (or cycles though all menu items with the same AccessKey if there are multiple).Been
@KlausGütter, it IS 11 years old. It certainly was correct then. Its good to see an update howeverRedhead
C
1

The character following the underscore is the AccessKey (not the "keyboard shortcut" aka KeyGesture as referred to in crthompson's answer).

When pressing the Alt key, the access keys of all menu items are displayed as underlined. Then typing the AccessKey

  • executes the command if only a single command has this access key
  • or cycles though all menu items with the same AccessKey if there are multiple.

In your example, this allows to quickly execute the Undo command by pressing Alt+E (to open the Edit menu) and then U (does not matter if you still hold the Alt key or release it before) to execute the Undo command.

This is all handled automatically by the Windows menu handler.

In contrast to this, a keyboard shortcut (e.g. usually Ctrl+Z for Undo) is independent of the menu and has to be implemented in code or by a WPF KeyBinding.

Cha answered 24/4, 2024 at 4:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.