【问题标题】:Restoring exact scroll position of a listbox in Windows Phone 7在 Windows Phone 7 中恢复列表框的精确滚动位置
【发布时间】:2010-12-17 23:04:47
【问题描述】:

我正在努力让应用程序从被墓碑中恢复过来。该应用程序包含大型列表框,因此我希望在用户滚动这些列表框时回滚到用户所在的位置。

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

有什么想法吗?

克里斯

【问题讨论】:

    标签: silverlight windows-phone-7 listbox


    【解决方案1】:

    您需要在内部获取ListBox 使用的ScrollViewer,以便获取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);
            }
        }
    }
    

    有了这个可用的ListBox(和所有其他的UIElements)得到了几个新的扩展方法DescendentsAncestors。我们可以将它们与 Linq 结合起来搜索东西。在这种情况下,您可以使用:-

    ScrollViewer sv = SomeListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault();
    

    【讨论】:

    • 非常感谢!我什至没有意识到控件的化妆可以通过这种方式进行导航。
    • 那么你怎么知道什么时候使用这些信息呢?一个页面如何知道它正在从墓碑恢复而不跳过一堆箍?
    • @Roger:读过这个 MSDN 主题:msdn.microsoft.com/en-us/library/ff967548(v=VS.92).aspx
    • 不应该foreach (var descendent in Descendents(child, --depth))foreach (var descendent in Descendents(child, depth - 1)) 吗?编写的代码将递归到第一个孩子的depth - 1,第二个孩子的depth - 2,等等。或者这是故意的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多