【问题标题】:Add Short Cut Key to button [duplicate]将快捷键添加到按钮[重复]
【发布时间】:2013-02-26 08:01:42
【问题描述】:

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

【问题讨论】:

标签: c# wpf


【解决方案1】:

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

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>

【讨论】:

  • 如何添加到多个窗口?
  • 在这个方法中你必须在每个窗口中编写这段代码
【解决方案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>

【讨论】:

  • 如何添加到多个窗口?
  • @AComputert:写一个继承自Window或UserControl的子类。然后在 YourWindow 中实现这些,然后使用它代替您想要的任何窗口。
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 2016-06-11
  • 2011-12-12
  • 2021-08-25
  • 2010-09-06
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
相关资源
最近更新 更多