title: Centering selected item in a scroll viewer
body: <p>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.</p>
  
  <p>The following links set me on the right track, but because of the limitation of the WinRT API, was not able to use them:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/2946954/make-listview-scrollintoview-scroll-the-item-into-the-center-of-the-listview-c">Make ListView.ScrollIntoView Scroll the Item into the Center of the ListView (C#)</a></li>
  <li><a href="http://blogs.msdn.com/b/delay/archive/2009/04/19/fewer-gotchas-to-getcha-enhancing-the-scrollintoviewcentered-method-for-wpf-s-listbox.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/delay/archive/2009/04/19/fewer-gotchas-to-getcha-enhancing-the-scrollintoviewcentered-method-for-wpf-s-listbox.aspx</a></li>
  </ul>
  
  <p>The desired effect is as follows:</p>
  
  <p><img src="https://i.stack.imgur.com/x7q26.png" alt="centered selected item in scrollviewer"></p>
  
  <p>This is a sample setup in my XAML:</p>
  
  <pre><code>&lt;ScrollViewer x:Name="MyScrollViewer"&gt;
      &lt;ListView x:Name="MyView" VerticalAlignment="Center"
                        SelectionChanged="Selector_OnSelectionChanged"&gt;
          &lt;ListView.ItemTemplate&gt;
              &lt;DataTemplate&gt;
                  &lt;Grid Width="80" Height="80" Margin="0"&gt;
                      &lt;TextBlock Text="{Binding}" /&gt;
                  &lt;/Grid&gt;
              &lt;/DataTemplate&gt;
          &lt;/ListView.ItemTemplate&gt;
          &lt;ListView.Items&gt;
              &lt;x:String&gt;1&lt;/x:String&gt;
              &lt;x:String&gt;2&lt;/x:String&gt;
              &lt;x:String&gt;3&lt;/x:String&gt;
              &lt;x:String&gt;4&lt;/x:String&gt;
              &lt;x:String&gt;5&lt;/x:String&gt;
              &lt;x:String&gt;6&lt;/x:String&gt;
              &lt;x:String&gt;7&lt;/x:String&gt;
              &lt;x:String&gt;8&lt;/x:String&gt;
              &lt;x:String&gt;9&lt;/x:String&gt;
          &lt;/ListView.Items&gt;
      &lt;/ListView&gt;
  &lt;/ScrollViewer&gt;
  </code></pre>
  
  <p>Knowing the index of the selected item, how do I calculate the vertical offset that I can use in my method:</p>
  
  <pre><code>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);
  }
  </code></pre>