我发现有很多关于冒泡的示例,但没有关于事件隧道的说明。这里是关于事件隧道的示例,例如从父级到子级传递事件。我认为我的主要问题在于不理解如何在子控件(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。