Silverlight 5
introduced the new ClickCount property of the MouseButtonEventArgs
class. This property tells you how many times the user has
rapidly clicked the mouse button. While this is useful for
supporting double click and triple (or even more) click scenarios,
it's not immediately obvious how you would use it to support both
in the same element. Several folks in the community, like
Kunal Chowdhury, have pointed out the issues with supporting
both, as have I in
my video on the topic.
Here's a quick way to deal with the issue. I'm not presenting
this as the perfect approach (especially as the timeout is pretty
picky and doesn't take OS mouse click speed settings into account),
but it works.
XAML
<Grid x:Name="LayoutRoot"
Background="White">
<Rectangle x:Name="ClickRectangle"
Height="85"
Width="93"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="30,40,0,0"
Stroke="Black"
StrokeThickness="1"
Fill="#FFE82A2A"
MouseLeftButtonDown="RectMouseLeftButtonDown" />
</Grid>
C# Source code
private TimeSpan _clickDelay = TimeSpan.FromMilliseconds(300);
private int _clickCount = 0;
private DispatcherTimer _timer = new DispatcherTimer();
void RectMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// This code would never allow for a triple click
//if (e.ClickCount == 2)
// MessageBox.Show("Double click!");
//else if (e.ClickCount == 3)
// MessageBox.Show("Triple click!");
_clickCount = e.ClickCount;
if (e.ClickCount >= 2 && !_timer.IsEnabled)
{
// wait to see if we get a triple click
_timer.Interval = _clickDelay;
_timer.Tick += TimerTick;
_timer.Start();
}
else if (e.ClickCount < 2)
{
_timer.Stop();
}
}
private void TimerTick(object sender, EventArgs e)
{
_timer.Stop();
_timer.Tick -= TimerTick;
if (_clickCount == 2)
OnRectDoubleClick();
else if (_clickCount == 3)
OnRectTripleClick();
}
private void OnRectDoubleClick()
{
MessageBox.Show("Double Click!");
}
private void OnRectTripleClick()
{
MessageBox.Show("Triple Click!");
}
This code introduces a small delay before it identifies
something as a double or triple click. That small delay allows
enough time to capture the triple click in triple-click scenarios.
Once the delay is passed, it counts the clicks and fires the
appropriate method. The key value is the _clickDelay TImeSpan set
to 300 milliseconds.
This would be great code to either wrap into a behavior or
encapsulate in your own class for your projects. You may want to
make the timeout configurable to support a breadth of click
speeds.