Tuesday, January 6, 2009

Detecting a Double Click in Silverlight 2

Nope! It's not supported. In Silverlight 2, you can only detect single clicks. So... here's a way of faking it.

First of all, you are going to need an integer variable indicating how much time between two consecutive clicks constitute a double click. In this example, I am setting it to 175 milliseconds.

private const int DOUBLE_CLICK_TIME = 175;  // milliseconds between MouseUp and subsequent MouseDown

Next, you will need a DateTime variable to store the time of the last MouseLeftButtonUp event. Initially, you can set this to DateTime.MinValue.

private DateTime _lastTimeClicked = DateTime.MinValue;

Next, you will need to assign event handlers for your object's MouseLeftButtonDown and MouseLeftButtonUp events. In this case, I want to detect the double click on an object named LayoutPanel.

this.LayoutPanel.MouseLeftButtonDown += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonDown);
this.LayoutPanel.MouseLeftButtonUp += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonUp);

Now implement the event handlers. In the Button Up event handler simply store the current time as the last time clicked. Then in the down event handler call the IsDoubleClicked Method.

void LayoutRoot_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
_lastTimeClicked = DateTime.Now;

void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
if (IsDoubleClick())
//Double Click Logic Here

Finally, implement the IsDoubleClick event. This method returns true if there has been a double click, and false if not. It simply measures the current time agains the time last clicked. If the elapsed time between the two is less than the time specified in the DOUBLE_CLICK_TIME constant previously defined, it returns true... indicating a double click.

private bool IsDoubleClick()
TimeSpan elapsed = DateTime.Now.Subtract(this._lastTimeClicked);
return elapsed.TotalMilliseconds < DOUBLE_CLICK_TIME;

So that's it. As with some of my other posts, I hope this information will become useless soon because it gets included in a future release of Silverlight, but in the mean time, you can use this simple workaround to get the double click functionality into your Silverlight applications.

No comments:

Post a Comment