Silverlight currently has full mouse support for single click. However, double click is a another story. In this tip I will show you how to implement double click. You can apply this technique for an individual control or even your entire page.
The key to accomplishing this is to check for two things:
- Measure the TimeSpan between two mouse clicks. Verify it is less than around 300 milliseconds.
- Make certain the mouse has not moved more than a few pixels.
To demonstrate this I have a DateTime member that tracks the time the first mouse left click occurred. I also keep track of whether this is the first click or not.
public DateTime _lastClick = DateTime.Now;
private bool _firstClickDone = false;
Next, I add an event to monitor for left mouse clicks:
this.MouseLeftButtonDown += new
MouseButtonEventHandler(MainPage_MouseLeftButtonDown);
Finally, in the event to monitor for mouse left clicks I do the following:
- If more than 300 milliseconds has passed or a first click has not occurred yet get a snapshot of the time for the first click.
- If we have clicked already and less than 300 milliseconds has passed verify the mouse has not moved more than a few pixels. If not, we have a double click.
The following code demonstrates this technique:
private void MainPage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
DateTime clickTime = DateTime.Now;
TimeSpan span = clickTime - _lastClick;
FirstClickTB.Text = "MS between clicks = " + span.TotalMilliseconds;
if (span.TotalMilliseconds > 300 || _firstClickDone == false)
{
DoubleClickTB.Text = "First click...";
_clickPosition = e.GetPosition(element);
_firstClickDone = true;
_lastClick = DateTime.Now;
}
else
{
Point position = e.GetPosition(element);
if (Math.Abs(_clickPosition.X - position.X) < 4 &&
Math.Abs(_clickPosition.Y - position.Y) < 4)
DoubleClickTB.Text = "Double Click!";
else
DoubleClickTB.Text = "Double Click failed due to mouse move!";
_firstClickDone = false;
}
}
Source: Tip16_DoubleClick.zip
[silverlight: Tip16_DoubleClick.xap]
Thank you, --Mike






