在Windows Phone 7中恢复列表框的确切滚动位置

Chr*_*Rae 8 silverlight listbox windows-phone-7

我正在努力让一个应用程序很好地从墓碑式回来.该应用程序包含大型列表框,所以我最好滚动回到用户在这些列表框中滚动时的位置.

跳回到特定的SelectedItem很容易 - 不幸的是,对我来说,我的应用程序从不需要用户实际选择项目,他们只是滚动它们.我真正想要的是某种MyListbox.ScrollPositionY,但它似乎不存在.

有任何想法吗?

克里斯

Ant*_*nes 10

您需要掌握内部ScrollViewer使用的内容,ListBox以便您可以获取VerticalOffset属性的值并随后调用该SetVerticalOffset方法.

这要求您从ListBox构成其内部的可视树中向下延伸.

我使用这个方便的扩展类,你应该添加到你的项目中(我必须把它放在博客上因为我不断重复它): -

public static class VisualTreeEnumeration
{
    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
    {
        int count = VisualTreeHelper.GetChildrenCount(root);
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(root, i);
            yield return child;
            if (depth > 0)
            {
                foreach (var descendent in Descendents(child, --depth))
                    yield return descendent;
            }
        }
    }

    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
    {
        return Descendents(root, Int32.MaxValue);
    }

    public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
    {
        DependencyObject current = VisualTreeHelper.GetParent(root);
        while (current != null)
        {
            yield return current;
            current = VisualTreeHelper.GetParent(current);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个ListBox(以及所有其他UIElements)可以获得一些新的扩展方法DescendentsAncestors.我们可以将这些与Linq结合起来搜索内容.在这种情况下,您可以使用: -

ScrollViewer sv = SomeListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • 不应该'foreach(后代(孩子, - 深度)中的后代)是'foreach(后代(孩子,深度 - 1)中的后代)`` 写入的代码将递归到第一个孩子的"深度 - 1",第二个孩子的"深度 - 2"等.或者这是有意的吗? (2认同)