Simple double click in Silverlight

I needed to pick up on a double click on an image in Silverlight but there is no event to handle this. It can be done quite easily using a DispatchTimer.  I am doing this for an image but you should be able to do it for any UIElement.

First I have imported the System.Windows.Theading namespace where the DispatchTimer lives.  In the constructor of the User Control containing the image I have instantiated the Timer and set its interval to 200 milliseconds, this is the amount of time allowed between clicks for it to be considered a double click.  I have also added a listener to the Tick event of the Timer which fires with each iteration.

 
using System.Windows.Threading;

public partial class Image : UserControl
{
    DispatcherTimer _timer;

    public Image()
    {
        InitializeComponent();

        _timer = new DispatcherTimer();
        _timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
        _timer.Tick += new EventHandler(_timer_Tick);
    }
}

My event handler for the Image’s MouseLeftButtonDown will check if the Timer has already been started, and if so we know this is a double click, if not we start the timer.  The first time the event is raised the timer won’t be started, but the second time, on the second click it will be so this is our double click.

private void imgImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (_timer.IsEnabled)
    {
        MessageBox.Show("Double Click");
    }
        else
    {
        _timer.Start();
    }
}

Finally I handle the Tick event of the Timer, and simply stop the timer so that after 200 milliseconds the timer is no longer active, and any subsequent clicks are not counted as the second click of a double click.

void _timer_Tick(object sender, EventArgs e)
{
    _timer.Stop();
}

This is a fairly basic and not very reusable but does the job for what I need.  You could also use the GetPosition property of MouseButtonEventArgs to make sure that the mouse hasn’t moved between clicks.

Posted on by Joe in Silverlight

Add a Comment