Sonntag, 19. September 2010

Windows Phone 7: Scrollbar Position after Thombstoning

If you want to give your users the privilege that they are at the same scroll position in a listbox at a Windows Phone 7 application after thombstoning you can use the following code snipplet (usage of the page state):

   1: protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
   2:     {
   3:       base.OnNavigatedFrom(e);
   4:  
   5:       // Remember scroll offset
   6:       try
   7:       {
   8:         ScrollViewer viewer = ((VisualTreeHelper.GetChild(listBox, 0) as FrameworkElement).FindName("ScrollViewer") as ScrollViewer);
   9:         State["scrollOffset"] = viewer.VerticalOffset;
  10:       }
  11:       catch { }
  12:     }
  13:  
  14:     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  15:     {
  16:       base.OnNavigatedTo(e);
  17:       object offset;
  18:  
  19:       // Return scroll offset
  20:       if (State.TryGetValue("scrollOffset", out offset))
  21:         listBox.Loaded += delegate
  22:         {
  23:           try
  24:           {
  25:             ScrollViewer viewer = ((VisualTreeHelper.GetChild(listBox, 0) as FrameworkElement).FindName("ScrollViewer") as ScrollViewer);
  26:             viewer.ScrollToVerticalOffset((double)offset);
  27:           }
  28:           catch { }
  29:         };
  30:     }

1 Kommentar:

  1. Hi Patric,

    Thank you for this code - very useful.

    There's a small mistake in your source in the OnNavigatedFrom method - it assumes there is already a key called scrollOffset in State (it needs to use State.Add, and of course State.ContainsKey to ensure it doesn't add it twice).

    Any ideas on how to do the same for LongListSelector from the silvelight toolkit for WP7? I think I can do it using the GetItemsInView method, but I would prefer to do it a different way.

    Thanks,

    Ian

    AntwortenLöschen