如何滚动到元素UWP [英] How to scroll to element in UWP

查看:871
本文介绍了如何滚动到元素UWP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以滚动到特定位置的ScrollViewer内

How can I scroll to specific position inside a scrollviewer?

 <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>



我试图滚动到特定元素在我的ScrollViewer,但我是新来UWP,我可以'T完全得到它的权利如何做到这一点。

I am trying to scroll to a specific element in my scrollviewer but I am new to UWP and I can't quite get it right how to do it.

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

I want to set the scroll position of MyScrollView in the second textblock on an event happening.

推荐答案

一个更好的解决方案是使用 ChangeView 而不是 ScrollToVerticalOffset / ScrollToHorizo​​ntalOffset ,因为后者是Windows 10已经过时了。

A better solution is to use ChangeView instead of ScrollToVerticalOffset/ScrollToHorizontalOffset since the latter is obsolete in Windows 10.

MyScrollView.ChangeView(null, abosulatePosition.Y, null, true);

您甚至可以启用按最后一个参数设置为<$滚动动画C $ C>假。

You can even enable scrolling animation by setting the last parameter to false.

有关完成的缘故,我创建了一个这样的扩展方法。

For the sake of completion, I've created an extension method for this.

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



因此​​,在这种情况下,只需要调用

So in this case, just need to call

this.MyScrollView.ScrollToElement(otherTb);

这篇关于如何滚动到元素UWP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆