How to get GridView.Selected Item's Scroll Position in Windows 8 Metro App

感情迁移 提交于 2019-12-04 16:20:32

There are a few aspects here.

  1. I think just gridView.ScrollIntoView(gridView.SelectedItem) should work. It's a bit asynchronous, so the code wouldn't immediately see it scrolled, but if you do something like await Task.Delay(100) - you might be able to see the ScrollViewer offset updated..
  2. If you want an animated scroll - you can use WinRT XAML Toolkit's ScrollViewer.ScrollToHorizontalOffsetWithAnimation() extension or if you are targeting Windows 8.1 - you can use the new ScrollViewer.ChangeView() method that supports animated scroll.
    1. You need to get the instance of the ScrollViewer in the GridView template first. You can either do it using GetTemplatePart() or with the VisualTreeHelper.
    2. Now you need to get the position of the UI container of the SelectedItem in the ScrollViewer. To do that you first need the container itself, which you can get using var container = gv.ContainerFromItem(gv.SelectedItem), but if the ItemsPanel of the GridView is virtualized - you might not be able to do that because the SelectedItem might not have its UI container. I would simply do the non-animated scroll in that case for many reasons - mainly performance, but if you really have to - you might be able to calculate the position based on the index of the SelectedItem in the collection of items and item size, but it might be a bit complicated.
    3. Once you get the container you can get its position with something like var horizontalOffset = gridViewItem.TransformToVisual(scrollViewer).TransformPoint(new Point()).X;
    4. At this point you should be able to scroll to the offset using the method you like.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!