如何获取给定WPF命令的快捷方式?

时间:2009-07-29 21:11:34

标签: .net wpf keyboard-shortcuts

给定一个带命令的WPF按钮,我如何获得指定的快捷方式(例如复制 - > Ctrl + C

3 个答案:

答案 0 :(得分:2)

您可以在此处使用您要查找的命令替换 ApplicationCommands.Copy

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

答案 1 :(得分:1)

抱歉,我认为这是您问题的实际答案:

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>

按钮会显示“新建”。

答案 2 :(得分:-2)

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

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