This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Commanding - Mouse Bindings

The one hundred and sixty-seventh part of the Windows Presentation Foundation Fundamentals tutorial is the last article to describe WPF commanding. This instalment explains how mouse actions can be used to execute commands.

Mouse Gestures

Sometimes it is useful to detect mouse actions only when they coincide with modifier keys being pressed. For example, you might want to make a single selection when the user clicks the left button but add an item to a selection if the CTRL key is pressed at the same time. You can identify these combinations using the Gesture property, instead of MouseAction.

The Gesture property can include one or more modifier keys and any of the previously mentioned mouse actions, separated using plus symbols (+). The modifier keys are selected from the ModifierKeys enumeration, which is the same one that we saw in the previous article. The options in the enumeration are:

  • None. The default option, specifying that no modifier keys are used.
  • Alt. Requires that an ALT modifier key is pressed.
  • Control. Requires that a CTRL modifier key is pressed.
  • Shift. Requires that a SHIFT modifier key is pressed.
  • Windows. Requires that the Windows logo modifier key is pressed.

Let's add two further mouse actions using gestures. Add the following XAML within the Window.InputBindings element. The first detects a right click whilst the CTRL key is pressed. The second detects a double-click of the left button if ALT is pressed.

<MouseBinding Gesture="Control+RightClick"
              Command="{Binding MessageCommand}"
              CommandParameter="Control-Right Click"/>
<MouseBinding Gesture="Alt+LeftDoubleClick"
              Command="{Binding MessageCommand}"
              CommandParameter="Alt-Left Double-Click"/>

Run the program and test the new mouse bindings.

21 June 2015