Is there a way to get notified when a child is added / removed from the WPF panel?

I can not find the event that will be fired when the child is added or removed from the WPF panel. Is there such an event, and I just missed it?

+3
source share
3 answers

Alternatively, you can wrap the panel in a UserControl (possibly called an ObservablePanel?), Which has an AddChild method that fires an event after an item is added to the panel.

+1
source

I could not find the event, but you can try Panel.OnVisualChildrenChanged.

+6
source

Panel.CreateUIElementCollection(...), , UIElementCollection. UIElementCollection Add, Remove ..

public class CustomPanel: Panel
{
    protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)
    {
        ObservableUIElementCollection uiECollection = new ObservableUIElementCollection(this, logicalParent);
        uiECollection.RaiseAddUIElement += OnUIElementAdd;


        return uiECollection;
    }
}

public class ObservableUIElementCollection : UIElementCollection
{
    public ObservableUIElementCollection(UIElement visualParent, FrameworkElement logicalParent)
        : base(visualParent, logicalParent)
    {

    }

    public event EventHandler<UIElement> RaiseAddUIElement;

    public override int Add(UIElement element)
    {
        OnRiseAddUIElementEvent(element);
        return base.Add(element);
    }

    protected virtual void OnRiseAddUIElementEvent(UIElement e)
    {
        // copy to avoid race condition
        EventHandler<UIElement> handler = RaiseAddUIElement;

        if (handler != null)
            handler(this, e);
    }


}
0

Source: https://habr.com/ru/post/1704673/


All Articles