Reputation: 1351
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
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
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
Reputation: 11820
I couldn't find an event, but you might try the Panel.OnVisualChildrenChanged
method.
Upvotes: 7