我发现了很多解释冒泡的例子,但没有一个是关于隧道的,这是关于隧道的,例如父母对孩子。我想我的主要问题是我不知道如何在子进程中注册路由的事件(从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);
}
}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
}
}在xaml中
<Grid>
<Border BorderBrush="black" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center" PreviewMouseLeftButtonUp="UserControl_PreviewMouseLeftButtonUp">
</Border>
</Grid>如果我忘了什么,请告诉我。问题是,路由的事件不能到达UserControl_PreviewMouseLeftButtonUp
发布于 2012-11-20 22:37:44
这不是隧道路由策略的工作方式。隧道化意味着事件将从根开始,沿着树路径一直到调用控件。例如,如果我们有下面的可视化树
Window
|
|--> SomeUserControl
|--> MyParent
|
|--> ChildView然后,如果MyParent将引发隧道事件,则隧道事件将访问:
和而不是
所以总而言之,冒泡事件将始终从引发事件的控件开始,并在可视化树的根部停止,而隧道事件将从可视化树的根部开始,并在引发事件的控件处结束(完全相同的路径,只是顺序相反)。
EDIT:您可以在MSDN's Routed Events Overview中阅读有关路由事件的更多信息。它也有一个很好的图像来演示这一点:

https://stackoverflow.com/questions/13475384
复制相似问题