Jan 29

Routed events in Silverlight

Posted in Silverlight      Comments Off on Routed events in Silverlight

Routed events were introduced by WPF and they’re responsible for enabling several advanced scenarios in that platform:

  • tunneling: in this case, the event is first raised in the root and goes “down the tree” until the source element that generated the event is reached;
  • bubbling: in this case, the event bubbles from the source element to the root element;
  • Direct: the event is only raised in the source element.

Once again, the use of routed events in Silverlight is limited. By default, it only exposes a couple of routed events and it only supports bubbling (ie, there’s no tunneling for routed events in Silverlight).In order to illustrate the bubbling feature, we’ll start running the following example:

<UserControl x:Class="Tests.test"
"" xmlns:x="" xmlns:my="clr-namespace:Tests"> <Canvas Width="150" Height="200" x:Name="cv"> <StackPanel x:Name="sp"> <TextBlock Text="Click me" x:Name="bt" /> </StackPanel> </Canvas> </UserControl>

And here’s the code-behind:

public partial class test : UserControl {
    public test() {
        bt.MouseLeftButtonDown += PrintInfo;
        sp.MouseLeftButtonDown += PrintInfo;
        cv.MouseLeftButtonDown += PrintInfo;
        MouseLeftButtonDown += PrintInfo;
    private void PrintInfo(
Object sender, MouseButtonEventArgs e) { var info = String.Format(
"elemento original: {0} - elemento actual: {1}n", ((FrameworkElement)e.OriginalSource).Name, ((FrameworkElement)sender).Name); MessageBox.Show(info); } }

If you run the previous sample, you’ll notice that the event bubbles from the button until it reaches the root user control. The MouseButtonEventArgs class ends up inheriting from the RoutedEventArgs class. Due to that, we can access the OriginalSource property and find out which object is responsible for the event that is bubbling. Notice that the MouseButtonEventArgs ends up adding the read/write Handled property: when you set it to true,the event won’t be propagated beyond the current element that is responsible for the event that is being fired.

Unfortunately,you can’t really create custom routed events in Siverlight. The reason is simple: there isn’t a public API for letting you do that (if you dig into the code of the MouseLeftButtonDown event instantiation, you’ll notice that routed events are created through the RoutedEvent constructor which is internal). What this means is that you’re limited to creating “normal” events in your custom classes. I’m not sure if this limitation will ever be removed from Silverlight. And I guess this sums it up quite nicely. Stay tuned for more on Siverlight.