我正在努力使应用程序从被墓碑化后很好地恢复。该应用程序包含大型列表框,因此我希望在用户滚动这些列表框时返回到用户所在的位置。
很容易跳回特定的 SelectedItem - 对我来说不幸的是,我的应用程序从不需要用户实际选择一个项目,他们只是滚动浏览它们。我真正想要的是某种 MyListbox.ScrollPositionY 但它似乎不存在。
有任何想法吗?
克里斯
最佳答案
你需要得到ScrollViewer
由 ListBox
使用在内部,您可以获取 VerticalOffset
的值属性(property),随后调用 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)获得了几个新的扩展方法 Descendents
和 Ancestors
.我们可以将它们与 Linq 结合起来进行搜索。在这种情况下,您可以使用:-ScrollViewer sv = SomeListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault();
关于silverlight - 在 Windows Phone 7 中恢复列表框的精确滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475537/