protected override Size MeasureOverride(Size availableSize) { var itemsControl = ItemsControl.GetItemsOwner(this); var itemCount = itemsControl.HasItems ? itemsControl.Items.Count : 0; var firstVisibleItemIndex = Math.Max(SelectedIndex - NumberVisible, 0); var lastVisibleItemIndex = Math.Min(SelectedIndex + NumberVisible, itemCount - 1); var children = InternalChildren; var generator = ItemContainerGenerator; var startPos = generator.GeneratorPositionFromIndex(firstVisibleItemIndex); var childIndex = (startPos.Offset == 0) ? startPos.Index : startPos.Index + 1; var inserted = 0; using (generator.StartAt(startPos, GeneratorDirection.Forward, true)) { for (var itemIndex = firstVisibleItemIndex; itemIndex <= lastVisibleItemIndex; ++itemIndex, ++childIndex) { bool newlyRealized; // Get or create the child var child = generator.GenerateNext(out newlyRealized) as UIElement; if (newlyRealized) { // Figure out if we need to insert the child at the end or somewhere in the middle if (childIndex >= children.Count) { AddInternalChild(child); inserted++; } else { InsertInternalChild(childIndex, child); inserted--; } if (child != null) { generator.PrepareItemContainer(child); } } } } CleanUpItems(firstVisibleItemIndex, lastVisibleItemIndex); if (StoredSelectedIndex != SelectedIndex) { StoredSelectedIndex = SelectedIndex; CurrentView.Anima(GetPositionIndex(SelectedIndex), NumberVisible, inserted); } if (availableSize.Width == double.PositiveInfinity || availableSize.Height == double.PositiveInfinity) { return(new Size()); } return(availableSize); }