Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoutedEvent Tunnel does not reach child

I found a lot of example explaining bubbling but none about Tunneling this is about Tunneling eg parent to child. I think my main problem is that i don't understand how to register the routed event in the child (WindowControl to UserControl). I got:

public partial class MyParent : UserControl
{
  public static readonly RoutedEvent RoutedMouseUpEvent = EventManager.RegisterRoutedEvent(
        "PreviewMouseLeftButtonUp", RoutingStrategy.Tunnel, typeof(RoutedEventHandler),   typeof(WindowControl)); 

// Provide CLR accessors for the event        
public event RoutedEventHandler MouseUp
{
  add { AddHandler(RoutedMouseUpEvent, value); }
  remove { RemoveHandler(RoutedMouseUpEvent, value); }
}

public addView(UserControl view)
{
WindowControl win = new WindowControl();
win.Content = view;
}

private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
  RoutedEventArgs newEventArgs = new RoutedEventArgs(MyParent.RoutedMouseUpEvent);
            RaiseEvent(newEventArgs);
}
}

The encapsulation of addView is necessary, should be no problem? The child is added via addView. Grid_MouseLeftButtonUp is called.
The receiver looks like this (It is mvvm so there isn't much):

public partial class ChildView : UserControl
{
 void UserControl_PreviewMouseLeftButtonUp(object sender, RoutedEventArgs args)
 {
    int i = 0; // The breakpoint is never called
 }
}

in the xaml

<Grid>
   <Border BorderBrush="black" BorderThickness="1" HorizontalAlignment="Center"   VerticalAlignment="Center" PreviewMouseLeftButtonUp="UserControl_PreviewMouseLeftButtonUp">
</Border>
</Grid>

If I forgot something please let me know. The problem is, that the routed event does not reach UserControl_PreviewMouseLeftButtonUp

like image 455
Martin Avatar asked Nov 20 '12 14:11

Martin


1 Answers

This is not how tunneling routing strategy works. Tunneling means that the event will start from the root and go down the tree path to the calling control. For example if we have the following visual tree

Window
|
|--> SomeUserControl
|--> MyParent
     |
     |--> ChildView

then if MyParent will raise a tunneling event, the tunneling event will visit:

  1. Window
  2. MyParent

and NOT

  1. MyParent
  2. ChildView

So to summarize, bubbling events will always start at the control raising the event and stop at the root of the visual tree, while tunneling events will start at the root of the visual tree and end at the control raising the event (exact same path, only reverse order).

EDIT: You can read more about routed events in MSDN's Routed Events Overview. It also has a nice image demonstrating this:

enter image description here

like image 55
Adi Lester Avatar answered Oct 16 '22 10:10

Adi Lester