We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
A while back I needed to add a double click event to a control that had no such event. The solution I came up with was to wrap that control inside a UserControl and use the UserControl’s DoubleClick event.
One of the readers commented about a better way to do it using Command Binding, here is what David N said:
You can also do this by adding an InputBinding to the Grid, that will translate a double click to an invocation of a RoutedCommand, then you can bind that to some handler code somewhere higher in the tree. Commands seem to be a neglected part of WPF, but are really quite useful especially if there are multiple actions that should end up triggering the same code (button, toolbar button, context menu, key combination, double click in the grid..). I just used a builtin command in this sample but of course you’d probably use a custom one.
I was faced with the same problem last week so I decided to give it a shot.
All you have to do is to define a RoutedUICommand object in the code behind of the control:
Here is how to initialize the command I used a static constructor for it:
The parameters are Text, Name and Owner. That’s it, we have just created our double click command.
Before we go on and use it we have to create a delegate to fire when the command executes.
We have created the command and the delegate, now it is time to attach them to one another. this is written in XAML and is placed in the Window.xaml file:
This tells the window to attach the delegate to the custom command we have defined. 2 things to note:
All that is left to do is connect the command to the Rectangle by using InputBinding and MouseGestures:
DoubleClicking the Rectangle will execute the Command and the delegate giving us this:
A very elegant solution which you can customize and use it for almost anything you need. You can download a sample project from out freebies page. Just grab our feed to get the password at the bottom.
Tags :CommandBindingDouble ClickDoubleClickGestureMouse DoubleClickMouseBindingMouseGestureRoutedUICommand
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd