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:

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:

ScrollViewer VerticalOffset and ViewportHeight properties tell us the index of the first visible item and how many items are visible altogether.

Animations will be started when a ListBox triggers SelectionChanged event.

All functionality responsible for running animations on per ListBox item basis will be nested in SelectionChanged event handler.

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.

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.