单击按钮滚动到对象(C#/Xaml)

本文关键字:Xaml 对象 按钮 滚动 单击 | 更新日期: 2023-09-27 18:25:03

有没有一种方法可以让xaml页面在单击按钮时滚动到特定对象?例如,我的页面顶部有三个按钮。我希望每个按钮都能将滚动查看器移动到页面的顶部、中间和底部。我怎样才能做到这一点?谢谢

单击按钮滚动到对象(C#/Xaml)

我试图创建Xaml并解决问题。这是我的解决方案。这是Xaml代码。

<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>           

这是.cs代码

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);
}

}