Double-click isn't as popular a mouse action as it once was. For
many, especially the elderly, clicking twice in the same spot
without moving the mouse in between, is actually quite challenging.
Nevertheless, double-click (and even triple click in some
specialized programs in 3d and music) is a necessary
capability.
Please note that this article and the attached sample code was
written using the Silverlight 5 Beta, available at MIX11 in April
2011, and updated for the Silverlight 5 RC.
Silverlight 5 has introduced the concept of a click count.
Rather than create dedicated double, triple, or septuple click
events, you can simply count the number of clicks using the
ClickCount property of the MouseButtonEventArgs class. This works
for both the left and right mouse buttons.
Implementing this yourself is non-trivial, as you have to take
into account some fairly fiddly timings, ensuring that two
consecutive single clicks aren't taken as a double-click unless the
second click happens within a specific time period after the
previous click. I'm happy to let the platform do that work for
me.
Project Setup
I created a simple Silverlight web project. In the
MainPage.xaml, I added a single red rectangle and wired up an event
handler for MouseLeftButtonDown.
<UserControl x:Class="MouseClickCountDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle x:Name="ClickMe"
Width="80"
Height="80"
MouseLeftButtonDown="ClickMe_MouseLeftButtonDown"
Fill="Red" />
</Grid>
</UserControl>
The only code-behind is simply an event handler that helps us
count the clicks.
Implementing Double Click
Inside the ClickMe_MouseLeftButtonDown event, I added some debug
code to write the number of clicks to the output window, and
display a "Double Click" message if there are two clicks in a
row.
private void ClickMe_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Click Count: " + e.ClickCount);
if (e.ClickCount == 2)
System.Diagnostics.Debug.WriteLine("Double Click");
}
That's all there is to it. I've been able to generate click
counts up into the hundreds before my finger started to protest.
There is no artificial limit on the number of clicks you can
respond to. Try clicking slowly and clicking quickly to get a feel
for how it responds.
Source code for the Silverlight 5 Beta version of this
application may be downloaded via the link below.
A video version of this tutorial will be on Silverlight.net
shortly.