Double-click in Silverlight

It’s a bit nonsense for me, but in Silverlight, there’s no double click event. A little annoying issue, but fortunately, we can craft our own double click with the help of the MouseLeftButtonUp event and a timer (I’ll show the bare minimum here, let’s call it the poor man’s double click).

First you need a timer. To avoid some nasty threading issues, we use the DispatcherTimer – it runs on the same thread as the Dispatcher. I created it as a private field of my UserControl, so I assume you did this too.

I also created an event for the double click, but it’s fairly convenient. The main interest is the MouseLeftButtonUp event, which looks like this:

private void Control_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
      if (_doubleClickTimer.IsEnabled)
        if (this.DoubleClick != null)
          this.DoubleClick(this, null);
        _doubleClickTimer.Interval = new TimeSpan(0, 0, 0, 0, 400);
        _doubleClickTimer.Tick += (o, e2) => _doubleClickTimer.Stop();

* This source code was highlighted with Source Code Highlighter.

The source code is pretty simple. First we check if our DispatcherTimer has an enabled state. If it does, it means that it’s already started. If it’s started, then it means that the user must have clicked once on the control. That’s because if the DispatcherTimer isn’t started, then the else branch will run, which does nothing more than start a timer with a reasonable 400 milliseconds double-click experience, sets that it should run only once, then starts it.

So if our timer was started that means we are no longer than 400 milliseconds after the first click, so we have a double click! And we fire the double click event. That’s all, use it, extend it as you wish.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: