Pages

Sunday 13 February 2011

How to make a fully animated ListBox in Windows Mobile 7

If you want to animate all ListBox items in a way similar to the WM7 embedded functionality please have a look at the following article.

Requirements: 
  • only items visible on the screen take part in an animation,
  • an animation kicks off when one of the the ListBox items is selected,
  • all items are animated apart from the one which is selected,
  • items are animated one by one from the bottom to the top of the screen,
  • when the animation is finished the application navigates to the another page. 

Solutions:
  1. If we want to detect visible ListBox items you need to get access to the ScrollViewer which is a part of a ListBox visual tree. To iterate through the visual tree we will be using the following method:
  2.    1:          private T FindDependencyObject<T>(DependencyObject dependencyObject)
       2:              where T : DependencyObject
       3:          {
       4:              DependencyObject d = dependencyObject;
       5:              while (!(d is T) && VisualTreeHelper.GetChildrenCount(d) > 0)
       6:                  d = VisualTreeHelper.GetChild(d, 0);
       7:              return d as T;
       8:          }
    ScrollViewer VerticalOffset and ViewportHeight properties tell us the index of the first visible item and how many items are visible altogether.
  3. Animations will be started when a ListBox triggers SelectionChanged event.
  4. All functionality responsible for running animations on per ListBox item basis will be nested in SelectionChanged event handler.
  5. Items will be animated one by one using Storyboards nested in DataTemplate resources. An animation of each item will be delayed with Storyboard BeginTime property which has to be populated in code based on an item position.
  6. The last animated item Completed event handler will be used to trigger NavigationService.Navigate(...) method.
Found problems:
When you run animations/storyboards in code you have to be aware of few pitfalls. It is not allowed to start an animations which has been started it means that you have to be aware of the animation state and stop it if necessary. In this particular case a user is able to change a selected item in the middle of the running animation  and this is the moment when we have to clean it up and start the whole process again.

Results:

Useful links:
  • https://www.silverlight.net/learn/quickstarts/animations/#advanced_animations
Source code: ListBoxAnimation.zip

2 comments:

  1. The Silverlight link doesn't work anymore, any other links to follow the tutorial?

    ReplyDelete
  2. I would recommend to use source code :-)

    ReplyDelete