AlfredBr
AlfredBr

Reputation: 1351

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

I can't find the event that would get fired when a child is added or removed from a WPF panel. Does such an event exist and I am just missing it?

Upvotes: 5

Views: 1980

Answers (3)

Marcin Machowski
Marcin Machowski

Reputation: 21

It's also possible to override Panel.CreateUIElementCollection(...), so it returns custom type derived from UIElementCollection. In UIElementCollection you can override Add, Remove, etc.

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);
    }


}

Upvotes: 1

Mike Pateras
Mike Pateras

Reputation: 15015

Alternatively, you could wrap your panel in a UserControl (perhaps called ObservablePanel?), which has an AddChild method that fires an event after adding the item to the panel.

Upvotes: 2

Robert Macnee
Robert Macnee

Reputation: 11820

I couldn't find an event, but you might try the Panel.OnVisualChildrenChanged method.

Upvotes: 7

Related Questions