/// <summary> /// Causes the object to scroll into view. /// </summary> /// <param name="item">Object to scroll.</param> public void ScrollIntoView(object item) { if ((null != TemplateScrollViewer) && Items.Contains(item)) { // If the element is virtualizing we have to scroll to the index of the element // we've selected. This will force the virtualizing panel to rerender the required // elements. Rect itemsHostRect; Rect listBoxItemRect; bool virtualizing = VirtualizingStackPanel.GetIsVirtualizing(this); if (!IsOnCurrentPage(item, out itemsHostRect, out listBoxItemRect)) { if (IsVerticalOrientation()) { if (virtualizing) { this.TemplateScrollViewer.ScrollToVerticalOffset(SelectedIndex); return; } // Scroll into view vertically (first make the right bound visible, then the left) double verticalOffset = TemplateScrollViewer.VerticalOffset; double verticalDelta = 0; if (itemsHostRect.Bottom < listBoxItemRect.Bottom) { verticalDelta = listBoxItemRect.Bottom - itemsHostRect.Bottom; verticalOffset += verticalDelta; } if (listBoxItemRect.Top - verticalDelta < itemsHostRect.Top) { verticalOffset -= itemsHostRect.Top - (listBoxItemRect.Top - verticalDelta); } TemplateScrollViewer.ScrollToVerticalOffset(verticalOffset); } else { if (virtualizing) { this.TemplateScrollViewer.ScrollToHorizontalOffset(SelectedIndex); return; } // Scroll into view horizontally (first make the bottom bound visible, then the top) double horizontalOffset = TemplateScrollViewer.HorizontalOffset; double horizontalDelta = 0; if (itemsHostRect.Right < listBoxItemRect.Right) { horizontalDelta = listBoxItemRect.Right - itemsHostRect.Right; horizontalOffset += horizontalDelta; } if (listBoxItemRect.Left - horizontalDelta < itemsHostRect.Left) { horizontalOffset -= itemsHostRect.Left - (listBoxItemRect.Left - horizontalDelta); } TemplateScrollViewer.ScrollToHorizontalOffset(horizontalOffset); } } } }