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



Question:

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?


Solution:1

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.


Solution:2

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


Solution:3

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »