2

I am working with WPF. I want to create keyboard shortcuts for my WPF application. I have created as following. The first command binding tag for "open" is working and command binding for exit is not working. I dont know what is the reason.

<Window.CommandBindings>
<CommandBinding Command="Open" Executed="CommandBinding_Executed"/>
<CommandBinding Command="Exit" Executed="CommandBinding_Executed_1" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Open" Key="O" Modifiers="control" />
<KeyBinding Command="Exit" Key="E" Modifiers="control"/>
</Window.InputBindings>

Above code is getting the following error:

Cannot convert string 'Exit' in attribute 'Command' to object of type 'System.Windows.Input.ICommand'. CommandConverter cannot convert from System.String. Error at object 'System.Windows.Input.CommandBinding' in markup file 'WpfApplication2;component/window1.xaml' Line 80 Position 25.

Ebad Masood
  • 2,389
  • 28
  • 46
havan
  • 79
  • 2
  • 13

1 Answers1

4

You problem is that there is no exit command. You'll have to roll your own.

See here for built-in ApplicationCommands

It's pretty easy to create your own, I use a static utility class to hold common commands that I use often. Something like this:

public static class AppCommands
{
    private static RoutedUICommand exitCommand = new RoutedUICommand("Exit","Exit", typeof(AppCommands));

    public static RoutedCommand ExitCommand
    {
        get { return exitCommand; }
    }

    static AppCommands()
    {
        CommandBinding exitBinding = new CommandBinding(exitCommand);
        CommandManager.RegisterClassCommandBinding(typeof(AppCommands), exitBinding);
    }
}

Then you should be able to bind it like this:

<KeyBinding Command="{x:Static local:AppCommands.Exit}" Key="E" Modifiers="control"/>
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • @havan: Well, there are several sets of commands already built into .NET. There's a set of ComponentCommands, MediaCommands, NavigationCommands and EditingCommands. But it's easy to create your own commands. I've edited my answer to show one way of doing it. Also, I have no idea why Microsoft neglected to add an ExitCommand to ApplicationCommands. – Matt Burland Mar 20 '12 at 13:41