I am trying to center a selected item in a ListView inside a ScrollViewer and struggling to calculate the vertical offset that I should be setting the ScrollViewer relative to the ListView.
The following links set me on the right track, but because of the limitation of the WinRT API, was not able to use them:
- Make ListView.ScrollIntoView Scroll the Item into the Center of the ListView (C#)
- http://blogs.msdn.com/b/delay/archive/2009/04/19/fewer-gotchas-to-getcha-enhancing-the-scrollintoviewcentered-method-for-wpf-s-listbox.aspx
The desired effect is as follows:
This is a sample setup in my XAML:
<ScrollViewer x:Name="MyScrollViewer">
<ListView x:Name="MyView" VerticalAlignment="Center"
SelectionChanged="Selector_OnSelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="80" Height="80" Margin="0">
<TextBlock Text="{Binding}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Items>
<x:String>1</x:String>
<x:String>2</x:String>
<x:String>3</x:String>
<x:String>4</x:String>
<x:String>5</x:String>
<x:String>6</x:String>
<x:String>7</x:String>
<x:String>8</x:String>
<x:String>9</x:String>
</ListView.Items>
</ListView>
</ScrollViewer>
Knowing the index of the selected item, how do I calculate the vertical offset that I can use in my method:
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
double maxVerticalOffset = MyScrollViewer.ExtentHeight - MyScrollViewer.ViewportHeight;
int selectedItemIndex = MyView.SelectedIndex;
double verticalOffset = ...
MyScrollViewer.ChangeView(null, verticalOffset, null);
}
Try
ListView.ScrollIntoView()
orListView.MakeVisible
first to scroll the container of the item into view and work around it being possibly virtualized out of the UI. Then useListView.ItemContainerGenerator
.
ContainerFromIndex
() to get the container of the item and then theVisualTreeHelper
to get its position relative to theScrollViewer
. Then scroll the scrollviewer by the calculated offset.*EDIT - Example positioning logic:
Get the VisualTreeHelperExtensions from WinRT XAML Toolkit to get access to the
ScrollViewer
easily withGetFirstDescendantOfType()
extension method that wraps some calls to theVisualTreeHelper
.XAML
C#
Yup, this worked for me out of the box with ScrollIntoView