tags:

views:

308

answers:

3

Given a WPF Button with a Command, how can I get the assigned shortcut (ex Copy -> Ctrl + C)

+2  A: 

Here you can replace ApplicationCommands.Copy with the command you are looking for.

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

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

 <Window.InputBindings>
    <KeyBinding Key="C"
          Modifiers="Control" 
          Command="ApplicationCommands.Copy" />
 </Window.InputBindings>
Jobi Joy
No, he is asking how do you get the keyboard shortcut, not how to add the KeyBinding.
Charlie
+1  A: 

Sorry I think this is the actual answer to your question:

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);
    }
}

If the reason you want to get is to display it in the button content, you can always do this:

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

That will have the button say "New".

Carlo