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.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With