0

如何在 wpf 中添加快捷键到按钮?我有三个带有新按钮的窗口,我想为所有窗口添加 Ctrl+N 或其他快捷方式。

4

2 回答 2

2

这是一个很棒的教程:https ://web.archive.org/web/20150430045153/http://tech.pro:80/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>
于 2013-03-11T07:57:00.567 回答
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>
于 2013-03-11T07:59:47.060 回答