1

Is there a way to have a xaml page scroll to a particular object on a button click? For example, I have three buttons at the top of my page. I would like each button to move the scrollviewer to the top, middle, and bottom section of the page. How can I make this happen? Thanks!

robbiestells
  • 265
  • 2
  • 18
  • I'd venture to guess you could just do a property change to the ScrollViewer VerticalOffset. Just take like 0 for top, content height size / 2 for middle, and content size height for bottom for example. – Chris W. Nov 30 '15 at 22:00
  • I think you want something like [this](http://stackoverflow.com/questions/32190237/how-to-scroll-to-element-in-uwp/32193216#32193216). – Justin XL Nov 30 '15 at 22:16

1 Answers1

1

I try to create the Xaml and to solve the problem. This is my solution. This is the Xaml code.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   <Grid.RowDefinitions>
       <RowDefinition Height="100"></RowDefinition>
       <RowDefinition Height="*"></RowDefinition>
   </Grid.RowDefinitions>

<Button HorizontalAlignment="Left" Content="Top" Click="Button_Click" ></Button>
<Button HorizontalAlignment="Center" Content="Center" Click="Button_Click_1" ></Button><Button Content="Botton" HorizontalAlignment="Right" Click="Button_Click_2" ></Button>
<ScrollViewer Grid.Row="1" Name="MyScrollViewer" MaxZoomFactor="9">
     <StackPanel>
          <TextBlock Name="TextBlock" Height="20"> </TextBlock>
          <Rectangle Height="300" Width="100"  Fill="BlanchedAlmond"></Rectangle>
          <Rectangle Height="300" Width="100"  Fill="Blue"></Rectangle>
          <Rectangle Height="300" Width="100"  Fill="BlueViolet"></Rectangle>
          <Rectangle Height="300" Width="100"  Fill="Chartreuse"></Rectangle>
          <Rectangle Height="300" Width="100"  Fill="Crimson"></Rectangle>
     </StackPanel>
</ScrollViewer>
</Grid>           

And this is the .cs Code

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyScrollViewer.ScrollToVerticalOffset(0);
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    var scrollableHeight = MyScrollViewer.ScrollableHeight;
    var height= scrollableHeight / 2;
    MyScrollViewer.ScrollToVerticalOffset(height);
}

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    MyScrollViewer.ScrollToVerticalOffset(MaxHeight);
}

}

Jayden
  • 3,276
  • 1
  • 10
  • 14