如何在 UWP 中滚动到元素 [英] How to scroll to element in UWP
问题描述
如何滚动到滚动查看器内的特定位置?
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>
我正在尝试滚动到我的滚动查看器中的特定元素,但我是 UWP 的新手,我不太清楚如何去做.
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
/ScrollToHorizontalOffset
因为后者在 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);
您甚至可以通过将最后一个参数设置为 false
来启用滚动动画.
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屋!