public override DataTemplate SelectTemplate(object item, DependencyObject container) { var parentItemsControl = VisualTreeHelpers.FindAncestorOrSelf <ItemsControl>(container); if ((item != null) && (parentItemsControl != null)) { var items = parentItemsControl.Items; if (items.IsEmpty) { return(null); } // if only one element is present if (items.Count == 1) { return(SingleElementTemplate); } var index = items.IndexOf(item); // if first item if (index == 0) { return(FirstElementTemplate); } // if last item if (!items.IsEmpty && (index == items.Count - 1)) { return(LastElementTemplate); } return(MiddleElementTemplate); } return(null); }