BlackWaspTM

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 Bindings

In the last instalment in the WPF tutorial we saw how key bindings could be employed to allow users to execute commands using keyboard shortcuts. A similar type of input binding can be used with mouse actions, allowing you to detect when the user clicks any of the three main mouse buttons, double-clicks a button or moves the mouse wheel.

Mouse bindings, like key bindings, are applied to any control or other object that inherits from the UIElement class. They are added to the item's InputBindings collection. In this article we'll demonstrate mouse bindings by applying several to a simple command and a basic window.

To begin, create a new WPF application in Visual Studio named, "MouseBindingDemo". Once the solution is ready, replace the XAML in the main window with the code below. This creates a window containing a Label.

<Window x:Class="MouseBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MouseBinding Demo" Height="200" Width="250">
    <Label HorizontalAlignment="Center" VerticalAlignment="Center">Mouse Binding Demo</Label>
</Window>

As with the previous article, let's create a simple custom command that shows the contents of its provided parameter. Add the following class to the project.

public class MessageCommand : ICommand
{
    public void Execute(object parameter)
    {
        MessageBox.Show(parameter.ToString());
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

To allow the window access to the command, we'll create a new class that will be the basis of the window's data context. This includes a property that provides an instance of the MessageCommand class.

Create a new class file named, "MyDataContext" and update the code, as follows:

public class MyDataContext
{
    ICommand _messageCommand = new MessageCommand();
 
    public ICommand MessageCommand
    {
        get { return _messageCommand; }
    }
}

Finally, to link all of the items together, update the constructor of the main window, as shown below. This creates a new instance of the MyDataContext class and assigns it to the data context of the window.

public MainWindow()
{
    InitializeComponent();
    DataContext = new MyDataContext();
}

Adding Mouse Bindings

Creating and using a mouse binding is very similar to the process for key bindings. You create a new MouseBinding object and add this to the target element's InputBindings collection. The action applies to the control that references it and its children within the logical tree.

To identify the control to execute, you set the Command property of the binding. This can specify a built-in command from the .NET framework or can be a binding expression that locates a custom command. Optionally, you can include a CommandParameter property. The contents of this property are passed to the command when it is run and when checking if it can be executed.

In addition to the command, you must specify the mouse action that you wish to capture. You can do this using the MouseAction member of the mouse binding. The property should be set to a value from the MouseAction enumeration. The actions that can be intercepted are:

  • LeftClick. Specifies that single left button clicks should be captured.
  • MiddleClick. Use this option to detect when the user clicks the middle button, which is often the mouse wheel.
  • RightClick. This option is used to capture the user clicking the right mouse button.
  • WheelClick. A mouse binding to the WheelClick option causes the command to execute when the mouse wheel is rotated.
  • LeftDoubleClick. Specifies that the command should run in response to the user double-clicking the left mouse button.
  • MiddleDoubleClick. This option is used to identify the user double-clicking the middle button.
  • RightDoubleClick. The final option runs the command when the right button is double-clicked.

NB: Left and Right are not ideal descriptions for the enumeration constants. If the user has reversed the operation of the mouse buttons in the operating system configuration, the LeftClick and LeftDoubleClick options will respond to the user clicking the right button. "Left" always signifies the primary button.

Let's define some mouse bindings. Create the following Window.InputBindings element. This captures double-clicking of all three main mouse buttons, and rotating of the wheel.

<Window.InputBindings>
    <MouseBinding MouseAction="LeftDoubleClick"
                  Command="{Binding MessageCommand}"
                  CommandParameter="Left Double Click"/>
    <MouseBinding MouseAction="MiddleDoubleClick"
                  Command="{Binding MessageCommand}"
                  CommandParameter="Middle Double Click"/>
    <MouseBinding MouseAction="RightDoubleClick"
                  Command="{Binding MessageCommand}"
                  CommandParameter="Right Double Click"/>
    <MouseBinding MouseAction="WheelClick"
                  Command="{Binding MessageCommand}"
                  CommandParameter="Wheel Click"/>
</Window.InputBindings>

Run the program and try the various mouse actions to see the results. When you double-click or move the mouse wheel, a message box will be displayed, showing the action taken.

21 June 2015