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

<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>

但是,当我运行示例时,在表示框架中得到的是空引用,该应用程序从不初始化,在尝试加载/初始化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;
}

我基本上是想复制ButtonBase.Click如何允许 parent 为 child 订阅任何button click()方法的行为。但是,除了ButtonBase.Click(),这似乎没有其他作用。也就是说,当我将自定义的WpfApplication5:SpecialEvent.Tap="Catcher_Tap"切换为ButtonBase.Click="Catcher_Tap"时,它可以工作。有什么想法吗?我不做的ButtonBase在做什么?

最佳答案

在玩了更多之后,我发现可以完成主窗口后面的代码中需要的内容,如下所示:

public MainWindow()
    {
        InitializeComponent();
        Root.AddHandler(SpecialEvent.TapEvent, new RoutedEventHandler(Catcher_Tap));
    }

由于某些原因,无法像在ButtonBase()中那样在XAML中指定它,但是在后面的代码中添加Handler可以。

关于WPF路由事件,订阅自定义事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11692231/

10-17 01:57