Correct way to create a menu with shortcuts in WPF

2019-02-15 02:42发布

问题:

What is the correct/best way to create a menu with hotkey shortcuts?

I simply want a File menu like Visual Studio's that has New, Open, Save, Save All, Exit, and a few other standard shortcuts.

It seems that InputGestureText displays the appropriate text, but since it's called "Text" and doesn't seem to trigger events, I'm going to assume that isn't the right way to do it. The Command architecture also seems fairly bulky, so I don't want to head down that path if there is a better way.

Update: For clarity, let's say I'm using the following menu:

<Menu>
  <MenuItem Header="_File">
    <MenuItem Header="_New" />
    <MenuItem Header="_Open" />
    <Separator />
    <MenuItem Header="_Save" />
    <MenuItem Header="Save _All" />
    <Separator />
    <MenuItem Header="_Export"/>
    <MenuItem Header="_Import"/>
    <Separator />
    <MenuItem Header="E_xit"/>
  </MenuItem>
</Menu>

where Export and Import would be custom shortcuts; something that Microsoft didn't build into something like ApplicationCommands. Can you please provide a complete solution, including C# custom code if necessary? (Not only will it help me out, but I hope to help anyone else out who is searching for similar issues.)

回答1:

You are correct in noting that InputGestureText does not actually set up a shortcut, it simply labels it on the menu. The correct way to do it is to use the InputBindings of the window. You can map a keyboard shortcut to any command, including your own model-defined commands. But in order for this to work, you need to use menu items bound to commands - not handle their click events directly. This is the recommended way of handling menu commands in WPF. Otherwise you'll need to resort to old fashioned keyboard event handling.

<Window.InputBindings>
  <KeyBinding Key="A" Modifiers="Control" Command="{Binding MyAwesomeCommand}" />
</Window.InputBindings>

More information on MSDN.



回答2:

Take a look at the ApplicationCommands class. You get the standard key gestures (accelerators) and text for free.

<MenuItem Command="ApplicationCommands.Paste" Width="75" />