WPF中让滚动条滚动到指定元素位置

    /// <summary>
    /// 垂直方向滚动到顶部
    /// </summary>
    /// <param name="element"></param>
    /// <param name="scrollViewer"></param>
    public static void ScrollViewToVerticalTop(FrameworkElement element, ScrollViewer scrollViewer)
    {
        var scrollViewerOffset = scrollViewer.VerticalOffset;
        var point = new Point(0, scrollViewerOffset);
        var tarPos = element.TransformToVisual(scrollViewer).Transform(point);
        scrollViewer.ScrollToVerticalOffset(tarPos.Y);
    }
    
    /// <summary>
    /// 水平方向滚动到右侧
    /// </summary>
    /// <param name="element"></param>
    /// <param name="scrollViewer"></param>
    public static void ScrollViewToHorizontalRight(FrameworkElement element, ScrollViewer scrollViewer)
    {
        var scrollViewerOffset = scrollViewer.HorizontalOffset;
        var point = new Point(scrollViewerOffset, 0);
        var tarPos = element.TransformToVisual(scrollViewer).Transform(point);
        scrollViewer.ScrollToHorizontalOffset(tarPos.X);
    }

如果需要滚动到中间需要减去容器的一半宽度或者高度

posted @ 2020-06-15 12:34  _York  阅读(117)  评论(0编辑  收藏