Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to element in UWP

Tags:

c#

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.

like image 352
Nejdi Kroi Avatar asked Aug 24 '15 19:08

Nejdi Kroi


1 Answers

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);
like image 156
Justin XL Avatar answered Sep 29 '22 04:09

Justin XL