Adding double click support in Silverlight

Posted in Programming, Silverlight by Ary Borenszweig on the June 24th, 2008

Silverlight Beta 2 doesn’t support double click, but since I needed it, I implemented it. I’ve created a class named Mouse. You create a Mouse instance that wraps an UIElement. The instance attaches itself to the MouseLeftDownButton and, using a timer, it allows you to recieve events when double click is performed.

Actually, you can detect as many clicks as you wish: the event arguments include the number of clicks performed by the user.

But I don’t want to attach to mouse events in code. I want to do it in XAML, like with MouseLeftButtonDown or Click. But, unfortunately, you can’t use attached properties whose type is an event handler. If you do that, you get an ugly exception.

“What a pity”, I thought, “now I need to remove some of my MouseLeftButtonDown events and replace them by code that creates Mouse instances and then attaching to Mouse events programatically”. But before doing that, I decided to give it another shot. What if I created an attached property whose type is string, and then at runtime I searched the method and invoke it?

The problem with that approach is that the method won’t be declared in the object where you are attaching the event, but probably in some parent control. For example:

<UserControl>
    <Rectangle manas:Mouse.Click=”SomeMethod” />
</UserControl>

SomeMethod is probably declared in our custom UserControl, not in Rectangle. But that poses no problem at all: just go up in the visual hierarchy throught the Parent property until we find a class that declares SomeMethod with the signature of our interest.

But, alas, at the time attached properties are processed by the XAML processor, the object in question is not yet in the visual hierarchy: it doesn’t have a parent. That’s no problem at all: we attach to the Loaded event and do the lookup in that moment, and we are guaranted that we can reach the parent we are interested in.

Once I did that I was really amazed that it worked! :-)

Then, I refactored the code so I could use that trick to support other custom event handlers in XAML as well. Finally, changing the old event handlers to start firing at double clicks instead of single clicks was a matter of seconds.

Here’s the full code in case someone finds it useful.

(+) Show Code

One Response to 'Adding double click support in Silverlight'

Subscribe to comments with RSS or TrackBack to 'Adding double click support in Silverlight'.


  1. on June 25th, 2008 at 10:14 pm

    [...] has just wrote a very useful post about supporting double click events in Silverlight 2.0. The approach he presents is really [...]

Leave a Reply