Going the InputBindings way: Part 4 - How to code Mouse Bindings

Link to part 3 of this series: Going the InputBindings way- Part 3 – What’s the WinRT equivalent of KeyBindings

Getting straight to the point, in this article, I will be explaining how to create command bindings to certain mouse events such a RightClick or a LeftDoubleClick among others.

To start off, create a WPF application in Visual Studio. In MainWindow.xaml, add the following code.

  <Window.InputBindings>
    <MouseBinding
      MouseAction="LeftClick"
      Command="{Binding KeyPressedCommand}" />
  </Window.InputBindings>

What the above XAML does is define a mouse binding for a left click of the mouse. When this action is performed, the KeyPressedCommand is executed since it is bound to the Command property of the MouseBinding. Now, the KeyPressedCommand should be defined as a property of the DataContext instance as follows.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.KeyPressedCommand = new RelayCommand(obj => MessageBox.Show("Test"));
            this.DataContext = this;
        }
        public ICommand KeyPressedCommand { get; private set; }
    }

In the above code snippet, I have initialized the KeyPressedCommand property of the MainWindow class and then made it it’s own view model by assigning it to the DataContext property. While I won’t go into details of the RelayCommand, for the purpose of this dicussion, suffice it to know that the lambda in the constructor is called when the command is executed. Also, if in the XAML, we specify the CommandParameter property, that value is used for the obj input parameter of the lambda. Otherwise it would be null.

In case want a customized action, such as perhaps left click when the control key is pressed (an useful scenario when you want to say select multiple items), instead of specifying the MouseAction property in the XAML, you could instead specify the Gesture property as Gesture="CTRL+LeftClick".

For more information on this subject you can refer to some of the articles below