将快捷键添加到按钮

时间:2013-03-11 07:51:35

标签: c# wpf

如何在wpf中添加快捷键到按钮? 我有三个带有New Button的窗口,我想为所有这些添加Ctrl + N或其他短片。

2 个答案:

答案 0 :(得分:2)

以下是一个很棒的教程:http://tech.pro/tutorial/839/wpf-tutorial-command-bindings-and-custom-commands

样本(取自上面的链接)

<Window x:Class="CustomCommandTest.CommandWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Custom Command Test" Height="300" Width="300">

  <Window.CommandBindings>
    <CommandBinding Command="Help" 
        CanExecute="HelpCanExecute"
        Executed="HelpExecuted" />
  </Window.CommandBindings>

  <Window.InputBindings>
    <KeyBinding Command="Help" Key="H" Modifiers="Ctrl"/>
    <MouseBinding Command="Help" MouseAction="LeftDoubleClick" />
  </Window.InputBindings>

  <StackPanel>
    <Button Command="Help" Content="Help Command Button" />
    <Button Content="My Command" x:Name="MyCommandButton" />
  </StackPanel>
</Window>

答案 1 :(得分:2)

您也可以按照以下方法进行操作。在表单写入方法中指示快捷键。

private void shortcutKey_Click(object sender, System.Windows.Input.KeyEventArgs e)
{
    if ((e.Key == Key.N) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
        ProjMnuBtn_AddProj_Click(null, null);
}

然后在xaml文件中你需要设置如下:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="1280" Height="920" KeyUp="shortcutKey_Click">

</Window>