问题
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()
回答1:
There are a few aspects here.
- 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 likeawait Task.Delay(100)- you might be able to see theScrollVieweroffset updated.. - 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 newScrollViewer.ChangeView()method that supports animated scroll.- You need to get the instance of the
ScrollViewerin theGridViewtemplate first. You can either do it usingGetTemplatePart()or with theVisualTreeHelper. - Now you need to get the position of the UI container of the
SelectedItemin theScrollViewer. To do that you first need the container itself, which you can get usingvar container = gv.ContainerFromItem(gv.SelectedItem), but if theItemsPanelof theGridViewis virtualized - you might not be able to do that because theSelectedItemmight 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 theSelectedItemin the collection of items and item size, but it might be a bit complicated. - Once you get the container you can get its position with something like
var horizontalOffset = gridViewItem.TransformToVisual(scrollViewer).TransformPoint(new Point()).X; - At this point you should be able to scroll to the offset using the method you like.
- You need to get the instance of the
来源:https://stackoverflow.com/questions/24033120/how-to-get-gridview-selected-items-scroll-position-in-windows-8-metro-app