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>
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.
I want to set the scroll position of MyScrollView in the second textblock on an event happening.
Solution 1:
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);
You can even enable scrolling animation by setting the last parameter to false
.
Update
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);
Solution 2:
I found the answer
var transform = otherTb.TransformToVisual(ContentsPanel);
Point absolutePosition = transform.TransformPoint(new Point(0,0));
MyScrollView.ScrollToVerticalOffset(absolutePosition.Y);
Update
In UWP ScrollToVerticalOffset is obsolete so
MyScrollView.ChangeView(null,absolutePosition.Y,null,true)
should be used instead. https://msdn.microsoft.com/en-us/library/windows/apps/dn252763.aspx