Question

I am selecting gridview item using code, so I also need my gridview to Scrolls at selected item's position , I tried GridView.ScrollintoPosition() but it is not working . IS there any way to get the Scroll position of SelectedItem so that I can scroll it using scrollViewer1.ScrollToHorizontalOffsetWithAnimation()

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top