简体   繁体   中英

How can I set shortkey for menus?

How can I set shortKey for menu for example , for this code :

<Menu >
    <MenuItem Header="File"  >
        <MenuItem Header="Save" ToolTip="Ctrl + S" Click="Save_Click"/>
        <MenuItem Header="Save As" ToolTip="Ctrl + S + Shift" Click="SaveAs_Click"/>
        <MenuItem Header="SelectAll" ToolTip="Ctrl + A" Click="SelectAll_Click"/>
    </MenuItem>
</Menu>

In other word when I pressed Ctrl-S , Save_Click would be raise and so on.

I think the best way is to use WPF Command pattern

<Window x:Class="MenuShotCuts.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.InputBindings>
        <KeyBinding Key="S" Modifiers="Ctrl"  Command="{Binding SaveCmd}" />
    </Window.InputBindings>
    <Grid>
        <Menu >
            <MenuItem Header="File"  >
                <MenuItem Header="Save" ToolTip="Ctrl + S" Command="{Binding SaveCmd}"/>
            </MenuItem>
        </Menu>
    </Grid>
</Window>

In code behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = this;

        m_saveCmd = new SaveCommand();
    }

    private SaveCommand m_saveCmd;
    public SaveCommand SaveCmd
    {
        get
        {
            return m_saveCmd;
        }
    }
}

public class SaveCommand : ICommand
{
    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        MessageBox.Show("Saved", "Info");
    }

    #endregion
}

As Igor said. However with you wish to avoid writing your own ICommand implementation you can add a CommandBinding for the Save and SaveAs commands.

<Window x:Class="MenuShotCuts.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Save"
                        Executed="SaveCommandHandler"
                    />
   </Window.CommandBindings>
   <!-- implementation -->
</Window>

You'll need to change the Command property of the MenuItem as well:

<MenuItem Header="Save" ToolTip="Ctrl + S" Command="ApplicationCommands.Save"/>

In the code behind:

// Save executed handler
private void SaveCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    // do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM