Wednesday, 30 November 2011

How to scroll ListBox (ScrollViewer) to show an element without using BringIntoView method

This is a problem you can encounter in WPF and Silverlight. The usual solution presented in the Internet is to use BringIntoView() method. This approach works but does not guarantee that the whole element will be showed. The solution I want to show you is similar in both technologies and is more precise than BringIntoView() method. 

Let's assume that our UI contains a ListBox with a content

   1:  <ListBox x:Name="SomeItems">
   2:  <!--...-->
   3:  </ListBox>

If we want to show a particular item contained in SomeItems ListBox we have to discover ScrollViewer which is a part of a ListBox visual tree and run ScrollToVerticalOffset method pointing to an index of an item we want to show. The following class can be used to find any DepenendecyObject in a visual tree.

   1:      public static class VisualHelper
   2:      {
   3:          public static T FindDependencyObject<T>(DependencyObject dependencyObject)
   4:      where T : DependencyObject
   5:          {
   6:              DependencyObject d = dependencyObject;
   7:              while (!(d is T) && VisualTreeHelper.GetChildrenCount(d) > 0)
   8:                  d = VisualTreeHelper.GetChild(d, 0);
   9:              return d as T;
  10:          }
  11:      }

This is how you can use the code presented above

   1:  var scrollViewer = VisualHelper.FindDependencyObject<ScrollViewer>(SomeItems);
   2:  scrollViewer.ScrollToVerticalOffset([index of an item]);

Friday, 4 November 2011


My first application has been released and is available on Windows Phone Marketplace