ScrollViewer 滚动到特定控件

ScrollViewer scroll to specific control

我有一个带有项目模板的滚动查看器。用户发送了一个控制号,我需要滚动到该项目。如何找到滚动查看器的偏移量?

这是我正在使用的滚动查看器

<ScrollViewer Grid.Row="0" x:Name="ScrollPanel" Padding="0">
    <Grid x:Name="TestPanel" >
        <ItemsControl x:Name="MainItemsControl" ItemsSource="{Binding PostList}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel x:Name="PostPanel" Margin="0,5,0,5">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="60" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Image x:Name="IconUrl" Source="{Binding IconUrl}" Grid.Row="0" Grid.Column="0" Margin="12,0,12,0" VerticalAlignment="Center" HorizontalAlignment="Center" Width="50"/>
                            <StackPanel Grid.Row="0" Grid.Column="1">
                                <TextBlock x:Name="PostAuthorName" Text="{Binding PostAuthorName}" TextWrapping="NoWrap" Margin="12,0,12,0" Foreground="Black" Style="{StaticResource PhoneTextNormalStyle}"/>
                                <TextBlock x:Name="PostTime" Text="{Binding PostTime}" TextWrapping="NoWrap" Margin="12,0,12,0" Foreground="Black" Style="{StaticResource PhoneTextSubtleStyle}"/>
                            </StackPanel>
                            <TextBlock x:Name="ReplyNumber" Text="{Binding ReplyNumber}" Grid.Row="0" Grid.Column="2" TextWrapping="NoWrap" Foreground="Black" Margin="12,0,12,0" Style="{StaticResource PhoneTextNormalStyle}" VerticalAlignment="Center"/>
                        </Grid>
                        <RichTextBox x:Name="PostContent" localcontrols:Properties.BBCode="{Binding PostContent}" />
                        <Rectangle Grid.Row="1"  Fill="Gray" Height="1" HorizontalAlignment="Stretch" Margin="0,10,0,10"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</ScrollViewer>

ItemsControl 未实现允许滚动到特定项目的逻辑。您可以改用 ListBox 控件。此控件有一个 ScrollIntoView 方法,该方法接受您要滚动到的对象作为参数。您仍然可以通过设置 ListBox 控件的 ItemsPanel 属性 来使用 RadWrapPanel。

您没有属性,但有两种方法:ScrollToVerticalOffset(垂直滚动)和 ScrollToHorizo​​ntalOffset(水平滚动)。

this.scrollViewer2.ScrollToVerticalOffset(0);

偏移量可以这样计算。代码取自this answer.

void ScrollToIndex(int index)
{
    var itemContainer = MainItemsControl.ItemContainerGenerator.ContainerFromIndex(index) as UIElement;
    GeneralTransform transform = itemContainer.TransformToVisual(ScrollPanel);
    Point position = transform.Transform(new Point(0, 0));
    ScrollPanel.ScrollToVerticalOffset(position.Y);
}