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);
    }

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

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

上一篇:C# 修改系统时间


下一篇:【????】UIWindow,UIView,CALayer的区别