【问题标题】:How can I get the shortcuts of a given WPF command?如何获取给定 WPF 命令的快捷方式?
【发布时间】:2009-07-29 21:11:34
【问题描述】:

给定一个带有命令的 WPF 按钮,我怎样才能获得分配的快捷方式(例如 Copy -> Ctrl + C

【问题讨论】:

    标签: .net wpf keyboard-shortcuts


    【解决方案1】:

    您可以在此处将 ApplicationCommands.Copy 替换为您要查找的命令。

    foreach (KeyBinding binding in InputBindings)
    {
        if (binding.Command == ApplicationCommands.Copy)
        {
            MessageBox.Show(binding.Modifiers.ToString() + " + " + binding.Key.ToString());
        }
    }
    

    【讨论】:

      【解决方案2】:

      对不起,我认为这是您问题的实际答案:

      Button b = new Button();
      
      b.Command = ApplicationCommands.Copy;
      
      List<string> gestures = new List<string>();
      
      if (b.Command is RoutedCommand)
      {
          RoutedCommand command =  (b.Command as RoutedCommand);
      
          foreach (InputGesture gesture in command.InputGestures)
          {
              if (gesture is KeyGesture)
              gestures.Add((gesture as KeyGesture).DisplayString);
          }
      }
      

      如果您想要获取的原因是在按钮内容中显示它,您可以随时这样做:

      <Button Command="ApplicationCommands.New" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"></Button>
      

      按钮会显示“新建”。

      【讨论】:

        【解决方案3】:

        使用 KeyBinding - http://msdn.microsoft.com/en-us/library/ms752308.aspx

         <Window.InputBindings>
            <KeyBinding Key="C"
                  Modifiers="Control" 
                  Command="ApplicationCommands.Copy" />
         </Window.InputBindings>
        

        【讨论】:

        • 不,他问的是如何获得键盘快捷键,而不是如何添加 KeyBinding。
        猜你喜欢
        • 2018-07-20
        • 2011-08-06
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 1970-01-01
        相关资源
        最近更新 更多