如何滚动到UWP中的元素

Nej*_*roi 10 c# uwp

如何滚动到滚动查看器中的特定位置?

 <ScrollViewer x:Name ="MyScrollView" HorizontalScrollBarVisibility="Hidden" Height="500">                      
   <StackPanel x:Name="ContentsPanel">
        <TextBlock x:Name="someTb" Height="50">
        </TextBlock>
        <TextBlock x:Name="otherTb" Height="100">
        </TextBlock>
   </StackPanel>
</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

我正在尝试滚动到我的滚动查看器中的特定元素,但我是UWP的新手,我无法完全理解如何做到这一点.

我想在事件发生时在第二个文本块中设置MyScrollView的滚动位置.

Jus*_* XL 24

更好的解决方案是使用ChangeView而不是ScrollToVerticalOffset/ ScrollToHorizontalOffset因为后者在Windows 10中已经过时.

MyScrollView.ChangeView(null, abosulatePosition.Y, null, true);
Run Code Online (Sandbox Code Playgroud)

您甚至可以通过将最后一个参数设置为来启用滚动动画false.


更新

为了完成,我为此创建了一个扩展方法.

public static void ScrollToElement(this ScrollViewer scrollViewer, UIElement element, 
    bool isVerticalScrolling = true, bool smoothScrolling = true, float? zoomFactor = null)
{
    var transform = element.TransformToVisual((UIElement)scrollViewer.Content);
    var position = transform.TransformPoint(new Point(0, 0));

    if (isVerticalScrolling)
    {
        scrollViewer.ChangeView(null, position.Y, zoomFactor, !smoothScrolling);
    }
    else
    {
        scrollViewer.ChangeView(position.X, null, zoomFactor, !smoothScrolling);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下,只需要打电话

this.MyScrollView.ScrollToElement(otherTb);
Run Code Online (Sandbox Code Playgroud)


Nej*_*roi 6

我找到了答案

    var transform = otherTb.TransformToVisual(ContentsPanel);
    Point absolutePosition = transform.TransformPoint(new Point(0,0));
    MyScrollView.ScrollToVerticalOffset(absolutePosition.Y);
Run Code Online (Sandbox Code Playgroud)

更新

在UWP中,ScrollToVerticalOffset已经过时了

    MyScrollView.ChangeView(null,absolutePosition.Y,null,true)
Run Code Online (Sandbox Code Playgroud)

应该用来代替.https://msdn.microsoft.com/en-us/library/windows/apps/dn252763.aspx