滚动到ScrollViewer中的Control

时间:2013-11-08 10:39:19

标签: windows-store-apps winrt-xaml

在我的windows store 8 metro风格的应用程序中,我有一个滚动查看器,用于滚动堆栈面板项目。 我希望在动态更改选区并且所选项目不在可见区域时自动滚动滚动条。

例如:这些选项卡是“部分”选项卡。当用户单击跳过按钮时,将跳过所选部分并选择下一部分。当用户跳过最后一部分然后他跳转到第一部分,但此处滚动查看器不会自动滚动到第一个选项卡,因为该用户无法在可见区域中看到所选部分。

3 个答案:

答案 0 :(得分:4)

这比你想象的容易。

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    var visual = MyRectangle.TransformToVisual(MyScrollViewer);
    var point = visual.TransformPoint(new Point(0, 0));

    // Windows 8.0
    MyScrollViewer.ScrollToVerticalOffset(point.Y);

    // Windows 8.1
    MyScrollViewer.ChangeView(null, point.Y, null);
}

使用此XAML

<ScrollViewer x:Name="MyScrollViewer">
    <StackPanel>
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle x:Name="MyRectangle" Fill="Red" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
        <Rectangle Fill="Wheat" Height="200" Width="200" Margin="10" />
    </StackPanel>
</ScrollViewer>

祝你好运!

答案 1 :(得分:1)

您可以使用ListView和ScrollIntoView方法。 或者您可以使用ScrollViewer类的ScrollToVerticalOffset方法,但您需要正确滚动项目的大小。

答案 2 :(得分:1)

根据Jerry的回答,下面的代码将更改Scroll Viewer的偏移量,以便控件位于ScrollViewer的视口中(如果它还没有)。

如果控件已经完全可见,则不会滚动滚动查看器。

var transform = control.TransformToVisual(MyScrollViewer);
var topLeft = transform.TransformPoint(new Point(0, 0));
var top = topLeft.Y;
var left = topLeft.X;
var bottom = top + control.ActualHeight;
var right = left + control.ActualWidth;

double? scrollToY = null;
if (top < 0)
{
    scrollToY = top + MyScrollViewer.VerticalOffset;
}
else if (bottom > MyScrollViewer.ViewportHeight)
{
    scrollToY = bottom + MyScrollViewer.VerticalOffset - MyScrollViewer.ViewportHeight;
}

double? scrollToX = null;
if (left < 0)
{
    scrollToX = left + MyScrollViewer.HorizontalOffset;
}
else if (right > MyScrollViewer.ViewportWidth)
{
    scrollToX = right + MyScrollViewer.HorizontalOffset - MyScrollViewer.ViewportWidth;
}

MyScrollViewer.ChangeView(scrollToX, scrollToY, null);

如果您只需要滚动一个轴,则可以删除不需要的轴的代码。

相关问题