WPF Mouse bindings

The following article discusses the WPF command binding feature with relation to Mouse clicks.

One of WPF powerful features is the binding of commands to controls. If you have used the MVVM design pattern, you will know how useful, powerful, easy, efficient and robust the application gets with WPF commands.

A simple scenario of a command binding would be,

<Window>
<Window.CommandBindings>
    <CommandBinding Command="Help"
       CanExecute="TestCommandCanExecute"
       Executed="TestCommandExecute" />
 </Window.CommandBindings>
<Grid>
 <Button Command="Help" Content="Click me" />
</Grid>
</Window>

When the button is clicked, first TestCommandCanExecute will be invoked and then as usual TestCommandExecute.

In addition to the simple scenarios of binding a command to a click event we also need to bind specific commands to specific events. For e.g., how about binding one command to Right Click and other to Left click ?
No problems at all. We can use the Mouse bindings to bind a specific command to a specific Mouse event.

Something like this,

<Button Content="Click Me">
    <Button.InputBindings>
        <MouseBinding Command="TestCommandLeft" MouseAction="RightClick" />
        <MouseBinding Command="TestCommandRight" MouseAction="RightClick" />
    </Button.InputBindings>
</Button>

The other Mouse actions supported for Mouse bindings are - LeftClick, RightClick, MiddleClick, WheelClick, LeftDoubleClick, RightDoubleClick, MiddleDoubleClick

Have fun.

Tags:

2 Responses to “WPF Mouse bindings”

  1. Anup Says:

    Hi,

    Cool stuff.

  2. Anonymous Says:

    This is really cool.

    Thanks Abitsmart.

    Cheers

Leave a Reply