We had to perform some business logic when a user double click’s on a Image, unfortunately till the current version of silverilght( version 4.x) there is no double click event. In future versions of silverlight we might get the double click functionality but for right now we will have to get this done by our self. So how do we implement double click event? The trick is to start a timer and check if the MouseLeftButtonDown event is fired again in certain duration(milliseconds).
Code is very simple and short, In the xaml we have a Image with a MouseLeftButtonDown event in the code behind we add a dispatch timer which is a part of System.Windows.Threading. On the first click start the timer, when next click event is fired check if the timer is active, if the timer is active then it is a double click so go ahead and perform the intended action.
The above functionality can be encapsulated in a class for a cleaner looking code. The class ‘DoubleClick’ has a dispatch timer and a public event. In the constructor you pass the UIElement as parameter and hook the MouseLeftButtonDown event. The timer tick event has an inline event handler defined that will stop the timer on the first tick.
A very interesting use of the Rx framework can simplify the above code to just couple of lines. In the MouseLeftButtonDown event we add a Observable.FromEvent and set TimeInterval, so when the event is fired for the first time the timer starts. On the second event the code in the body of lambda will be executed which checks if duration is greater then 300.
The above code is helpful for application that handles the logic directly in the codebehind, so how about MVVM application where the application logic is handled in the model view. A decent solution for such a scenario would be to write a behavior that implements the double click functionality. There are many posts which explain how to create a behaviors so I will not go in details, basically this double click behavior have a dependency property named as DoubleClickCommand that will bind to a property in the view model of type ICommand. I created a class called as DelegateCommand which implements the interface ICommand, this class will be instantiated in the view model and assigned to view models property.
Here is the code for the MainPage.xaml.cs
Here is the xaml for the MainPage.xaml.
Extending Silverlight mouse events
SharpGIS has a very interesting blog post about extending the silverlight mouse events. Including double-clicks they have provided many more extensions with source code and a online demo.