private static void OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { LoopPanel lp = sender as LoopPanel; DependencyObject target = e.TargetObject as DependencyObject; if (lp.BringChildrenIntoView && target != lp) { UIElement child = null; while (target != null) { if ((target is UIElement) && lp.InternalChildren.Contains(target as UIElement)) { child = target as UIElement; break; } target = VisualTreeHelper.GetParent(target); if (target == lp) { break; } } if (child != null && lp.InternalChildren.Contains(child)) { e.Handled = true; // determine if the child needs to be brought into view GeneralTransform childTransform = child.TransformToAncestor(lp); Rect childRect = childTransform.TransformBounds(new Rect(new Point(0, 0), child.RenderSize)); Rect intersection = Rect.Intersect(new Rect(new Point(0, 0), lp.RenderSize), childRect); // if the intersection is different than the child rect, it is either not visible // or only partially visible, so adjust the Offset to bring it into view if (!DoubleHelper.AreVirtuallyEqual(childRect, intersection)) { if (!intersection.IsEmpty) { // the child is already partially visible, so just scroll it into view lp.Scroll((lp.Orientation == Orientation.Horizontal) ? (DoubleHelper.AreVirtuallyEqual(childRect.X, intersection.X) ? childRect.Width - intersection.Width + Math.Min(0, lp.RenderSize.Width - childRect.Width) : childRect.X - intersection.X) : (DoubleHelper.AreVirtuallyEqual(childRect.Y, intersection.Y) ? childRect.Height - intersection.Height + Math.Min(0, lp.RenderSize.Height - childRect.Height) : childRect.Y - intersection.Y)); } else { // the child is not visible at all lp.Scroll((lp.Orientation == Orientation.Horizontal) ? (DoubleHelper.StrictlyLessThan(childRect.Right, 0.0d) ? childRect.X : childRect.Right - lp.RenderSize.Width + Math.Min(0, lp.RenderSize.Width - childRect.Width)) : (DoubleHelper.StrictlyLessThan(childRect.Bottom, 0.0d) ? childRect.Y : childRect.Bottom - lp.RenderSize.Height + Math.Min(0, lp.RenderSize.Height - childRect.Height))); } } } } }
public override void OnApplyTemplate() { LoopPanel = GetDescendantByType(this, typeof(LoopPanel)) as LoopPanel; base.OnApplyTemplate(); }