- The selected item should be always visible
- In addition it should be displayed in the middle of the list when possible (it's not possible for the first element).

The first requirement is quite easy to fulfill by using ListView.ScrollIntoView()
Solution
Instead of working with the ListView directly I worked with the included ScollView control. Here is my method for scrolling with some comments:public void ScrollToSelected(ListView list, Object selected) { var scrollViewer = list.GetFirstDescendantOfType<ScrollViewer>(); if (scrollViewer == null) return; // Calculate the offset to be used for scrolling. // In my case I use ViewPort height, index of the selected item and a fixed value 3 to adjust the result double halfList = scrollViewer.ViewportHeight/2; int itemIndex = list.Items.IndexOf(selected); double scrollOffset = itemIndex - halfList + 3; // If offset happens to be bigger than scrollable height use the scrollable height // Possible for items from the end of the list if (scrollOffset > scrollViewer.ScrollableHeight) { scrollOffset = scrollViewer.ScrollableHeight; } // scroll to calculated offset scrollViewer.ScrollToVerticalOffset(scrollOffset); }
No comments:
Post a Comment