/// <summary> /// Gets the Panel that contains the containers of an ItemsControl. /// </summary> /// <param name="control">The ItemsControl.</param> /// <returns> /// The Panel that contains the containers of an ItemsControl, or null /// if the Panel could not be found. /// </returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="control" /> is null. /// </exception> public static Panel GetItemsHost(this ItemsControl control) { if (control == null) { throw new ArgumentNullException("control"); } // Get the first live container DependencyObject container = control.ItemContainerGenerator.ContainerFromIndex(0); if (container != null) { return(VisualTreeHelper.GetParent(container) as Panel); } FrameworkElement rootVisual = control.GetVisualChildren().FirstOrDefault() as FrameworkElement; if (rootVisual != null) { ItemsPresenter presenter = rootVisual.GetLogicalDescendents().OfType <ItemsPresenter>().FirstOrDefault(); if (presenter != null && VisualTreeHelper.GetChildrenCount(presenter) > 0) { return(VisualTreeHelper.GetChild(presenter, 0) as Panel); } } return(null); }