Search code examples
c#wpfcommandbinding

how to add multiple command bindings in wpf


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.


Solution

  • 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"/>