ListView的精确滚动位置

时间:2015-03-20 10:54:25

标签: listview windows-runtime windows-phone-8.1

我想保存ListView的位置然后加载它,以便ListView显示在之前的确切位置。 ListView.ScrollIntoView()不够准确。

1 个答案:

答案 0 :(得分:3)

使用VerticalOffset属性获取偏移量,然后使用ScrollToVerticalOffset重置它。由于它们位于ScrollViewer,因此您需要从可视化树中提取它。请注意,此代码假定您没有重新模板ListView。此示例假定对象名为myListView

ScrollViewer scrollViewer;
double offset;

public MainPage()
{
  this.InitializeComponent();

  // Have to wait until the templates have been created
  SizeChanged += MainPage_SizeChanged;
}

void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
  // Assumes default template
  scrollViewer = VisualTreeHelper.GetChild(
    VisualTreeHelper.GetChild(myListView, 0), 0) as ScrollViewer;

  // Not needed any more
  SizeChanged -= MainPage_SizeChanged;
}

private void GetOffsetClicked(object sender, RoutedEventArgs e)
{
  offset = scrollViewer.VerticalOffset;
}

private void SetOffsetClicked(object sender, RoutedEventArgs e)
{
  scrollViewer.ScrollToVerticalOffset(offset);
}