我发现了很多解释冒泡的例子,但没有关于隧道的,这是关于隧道的,例如父母对孩子。我认为我的主要问题是我不明白如何在孩子中注册路由事件(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
}
}
在xml中
<Grid>
<Border BorderBrush="black" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center" PreviewMouseLeftButtonUp="UserControl_PreviewMouseLeftButtonUp">
</Border>
</Grid>
如果我忘记了什么,请告诉我。问题是,路由事件没有到达 UserControl_PreviewMouseLeftButtonUp