/// <summary> /// Called when the <see cref="Children"/> collection changes. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e) { List <Control> controls; switch (e.Action) { case NotifyCollectionChangedAction.Add: controls = e.NewItems.OfType <Control>().ToList(); LogicalChildren.InsertRange(e.NewStartingIndex, controls); VisualChildren.InsertRange(e.NewStartingIndex, e.NewItems.OfType <Visual>()); break; case NotifyCollectionChangedAction.Move: LogicalChildren.MoveRange(e.OldStartingIndex, e.OldItems.Count, e.NewStartingIndex); VisualChildren.MoveRange(e.OldStartingIndex, e.OldItems.Count, e.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: controls = e.OldItems.OfType <Control>().ToList(); LogicalChildren.RemoveAll(controls); VisualChildren.RemoveAll(e.OldItems.OfType <Visual>()); break; case NotifyCollectionChangedAction.Replace: for (var i = 0; i < e.OldItems.Count; ++i) { var index = i + e.OldStartingIndex; var child = (IControl)e.NewItems[i]; LogicalChildren[index] = child; VisualChildren[index] = child; } break; case NotifyCollectionChangedAction.Reset: throw new NotSupportedException(); } InvalidateMeasure(); }