#1,086 – Defining a Key Binding in XAML

You define a KeyBinding object to bind a key gesture (i.e. keypress) to a particular command.  You can do this in code by creating a KeyBinding instance and adding it to an UI elements InputBindings collection.

You can also define a key binding in XAML, as shown below.  You use a <KeyBinding> element for each key binding.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Commands" Width="320" Height="220">

    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Open"
                        Executed="Executed_Open"
                        CanExecute="CanExecute_Open"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Command="ApplicationCommands.Open"
                    Gesture="Ctrl+O"/>
    </Window.InputBindings>

    <StackPanel/>
</Window>

Here is the code-behind, containing methods for Executed and CanExecute.

        public void Executed_Open(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Executing the Open command");
        }

        public void CanExecute_Open(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
Advertisements

#1,084 – A KeyBinding Binds a Command to a Key

A user interface element has a CommandBindings collection containing command binding objects that indicate which commands are supported for the element and the code that the command is bound to.

User interface elements also have an InputBindings collection that contains KeyBinding and MouseBinding instances, each of which maps keyboard or mouse input to a command that is also present in the CommandBindings collection.

In the code below, we wire up the Open command for both key (Ctrl+O) and mouse (Ctrl+Left Click) input.

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open,
               (sender, e) => { MessageBox.Show("Executing the Open command"); },
               (sender, e) => { e.CanExecute = CanOpenIsChecked; }));

            // Ctrl+O = Open
            this.InputBindings.Add(new KeyBinding(ApplicationCommands.Open,
                new KeyGesture(Key.O, ModifierKeys.Control)));

            // Ctrl+Left Mouse Click = Open
            this.InputBindings.Add(new MouseBinding(ApplicationCommands.Open,
                new MouseGesture(MouseAction.LeftClick, ModifierKeys.Control)));
        }

We can now use either form of input to execute the Open command.

1084-001