从Unloaded事件处理程序引发的RoutedEvent不冒泡

问题描述

我有一个自定义用户控件,该控件继承自ItemsControl。通过ItemTemplate,它为ObservableCollection中的每个附加ViewModel创建一个ChildControl。

public class ChildControl : FrameworkElement
{
    public static readonly RoutedEvent CreatedEvent = EventManager.RegisterRoutedEvent(
        nameof(Created),RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(ChildControl));

    public static readonly RoutedEvent RemovedEvent = EventManager.RegisterRoutedEvent(
        nameof(Removed),typeof(ChildControl));

    public ChildControl
    {
        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
    }

    public event RoutedEventHandler Created
    {
        add => AddHandler(CreatedEvent,value);
        remove => RemoveHandler(CreatedEvent,value);
    }

    public event RoutedEventHandler Removed
    {
        add => AddHandler(RemovedEvent,value);
        remove => RemoveHandler(RemovedEvent,value);
    }

    private void OnLoaded(object sender,RoutedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(CreatedEvent));
    }

    private void OnUnloaded(object sender,RoutedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(RemovedEvent));
    }
}

和CustomItemsControl

public class CustomItemsControl : ItemsControl
{
    public CustomItemsControl()
    {
        AddHandler(ChildControl.CreatedEvent,new RoutedEventHandler(OnCreatedEvent));
        AddHandler(ChildControl.RemovedEvent,new RoutedEventHandler(OnRemovedEvent));
    }
    
    private void OnCreatedEvent(object sender,RoutedEventArgs e)
    {
        // stuff
    }

    private void OnRemovedEvent(object sender,RoutedEventArgs e)
    {
        // stuff
    }
}

除了RemovedEvent处理程序之外,其他所有功能都可以正常工作。当在ChildControl的Unloaded事件处理程序中引发事件时,CustomItemsControl不会捕获该事件。但是,假设在Loaded事件处理程序中调用RemovedEvent时,它就会被CustomItemsControl捕获。因此证明一切都已顺利完成。

我做错了什么吗?或者这意味着在设计时没有对从Unloaded事件处理程序中调用的RoutedEvents进行冒泡?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)