RoutedEvent隧道未到达儿童

Mar*_*tin 5 c# wpf routed-events

我找到了很多解释冒泡的例子,但没有关于隧道这是关于隧道,例如父母对孩子.我认为我的主要问题是我不明白如何在子节点中注册路由事件(WindowControl到UserControl).我有:

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);
}
}
Run Code Online (Sandbox Code Playgroud)

addView的封装是必要的,应该没问题吗?通过addView添加子项.调用Grid_MouseLeftButtonUp.
接收器看起来像这样(它是mvvm所以没有太多):

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

在xaml

<Grid>
   <Border BorderBrush="black" BorderThickness="1" HorizontalAlignment="Center"   VerticalAlignment="Center" PreviewMouseLeftButtonUp="UserControl_PreviewMouseLeftButtonUp">
</Border>
</Grid>
Run Code Online (Sandbox Code Playgroud)

如果我忘记了什么,请告诉我.问题是,路由事件没有到达UserControl_PreviewMouseLeftButtonUp

Adi*_*ter 11

这不是隧道路由策略的工作原理.隧道意味着事件将从根开始并沿着树路径向下到达调用控件.例如,如果我们有以下可视化树

Window
|
|--> SomeUserControl
|--> MyParent
     |
     |--> ChildView
Run Code Online (Sandbox Code Playgroud)

然后,如果MyParent将引发隧道事件,隧道事件将访问:

  1. 窗口
  2. 我的父母

不是

  1. 我的父母
  2. ChildView

总而言之,冒泡事件总是从引发事件的控件开始并停在可视化树的根部,而隧道事件将从可视树的根开始,并在控件上结束事件(完全相同的路径,只有逆序).

编辑:您可以在MSDN的路由事件概述中阅读有关路由事件的更多信息.它还有一个很好的图像来证明这一点:

在此输入图像描述

  • 现在我明白了。隧道无法到达我的孩子,这使得它在我看来毫无用处。我确实阅读了那些码头,但不知何故不以这种方式理解。我将使用接口解决我的问题并简单地传递数据(这是 B 计划)。谢谢你的精彩解释。 (2认同)