WPF路由事件,订阅自定义事件

lan*_*ncz 4 wpf routed-events

我正在尝试使用子控件进行路由事件,这些事件将手动触发这些事件,并且它们将冒泡并在主网格级别处理.我基本上想做这样的事情:

<Grid Name="Root" WpfApplication5:SpecialEvent.Tap="Catcher_Tap">
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="40" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <WpfApplication5:UserControl2 Grid.Row="0" x:Name="Catcher" />
    <WpfApplication5:UserControl1 Grid.Row="1" />
    <Frame Grid.Row="2" Source="Page1.xaml" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

但是,当我跑我的例子,我得到的演示框架空引用,应用程序初始化从来没有,它没有当它试图加载/初始化XAML(在InitializeComponent()).这是包含事件的小文件:

public class SpecialEvent
{
    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
        "Tap", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(UserControl1));

    // Provide CLR accessors for the event
    public event RoutedEventHandler Tap;
}
Run Code Online (Sandbox Code Playgroud)

我基本上想要复制ButtonBase.Click允许父母为他们的孩子订阅任何按钮click()方法的行为.但是,除了ButtonBase.Click()之外,这似乎并不起作用.也就是说,当我将我的自定义切换WpfApplication5:SpecialEvent.Tap="Catcher_Tap"ButtonBase.Click="Catcher_Tap"它的工作原理时.有什么想法吗?什么是ButtonBase,我不做什么?

lan*_*ncz 6

在玩了一些之后,我发现可以在主窗口的代码中完成我需要的东西,如下所示:

public MainWindow()
    {
        InitializeComponent();
        Root.AddHandler(SpecialEvent.TapEvent, new RoutedEventHandler(Catcher_Tap));
    }
Run Code Online (Sandbox Code Playgroud)

出于某种原因,像在ButtonBase()中那样在XAML中指定它不起作用,但Handler在后面的代码中添加了它.