Share via


Handling Mouse Input Events on Controls

As you probably already know, Silverlight 3 Beta shipped earlier this week. There is an absolute ton of new features in this release which are getting a lot of coverage; Perspective 3D, Pixel Shaders, H264 support, out of browser applications, and lots more.

I wanted to talk about one tiny new feature that, while it didn't recieve the fanfare than some of the other new features got, is still a great addition to Silverlight. What is this feature? Well, using it looks like this:

element.AddHandler(FrameworkElement.MouseLeftButtonDownEvent,

    new MouseButtonEventHandler(ElementMouseLeftButtonDown),

    true);

Admittedly, it doesn't look like much; it's just an alternative syntax for registering an event hander for a mouse event (instead of the usual += syntax). But it is the last parameter, "handledEventsToo", that is interesting. This lets your event handler register to be called even for events that get marked as handled by another event handler. This allows a Silverlight application developer to get around an annoying limitation in Silverlight 2: since Controls (such as Button) mark MouseLeftButtonDown and MouseLeftButtonUp events as handled, there was no way for a Panel to know that one of its child Controls was clicked on. It was possible for elements such as Shapes and Images but not for Controls like Button and ListBox.

In WPF, this was never a problem, since it has both bubbling routed events and tunnelling routed events (aka "Preview" events); Silverlight only has bubbling events.

You can read more about this method in the Silverlight 3 Beta documentation on MSDN