[Windows (Phone) 8] Start an animation on the selected ListBoxItem during ListBox’ SelectionChange event

January 9th, 2014 | Posted by Tom in .NET | Article | Windows 8 | Windows Phone | Read: 11,621

Ok, I admit the title is a bit long and you may wonder what I’m talking about so let me explain.

On the application I’m working, I use a Listbox to display items and I wanted to start an animation when an item is selected. Of course, I could have simply edit the ListBoxItem style and modify the “Selected” visual state (as explained here) but, in my case, I wanted to be notified when the animation was finished (to redirect the user on another page).

So here is the solution I’ve found. On the SelectionChanged event handler, retrieve the current ListBoxItem:

private async void OnCategoriesSelected(object sender, SelectionChangedEventArgs e)
    if (e.AddedItems != null && e.AddedItems.Count > 0 && e.AddedItems[0] != null)
        // The Listbox is bound to a List<Category> so when I get the AddedItems, I know they are of type Category.
        var selectedCategory = e.AddedItems[0] as Category;
        if (selectedCategory != null)
            var listBoxItem = this.CategoriesListBox.ItemContainerGenerator.ContainerFromItem(selectedCategory) as ListBoxItem;
            if (listBoxItem != null)

Now that I have the ListBoxItem object, I simply create a Storyboard and begin it:

listBoxItem.RenderTransform = new CompositeTransform();

var swipeAnimation = new DoubleAnimationUsingKeyFrames();
swipeAnimation.KeyFrames.Add(new EasingDoubleKeyFrame
    Value = App.RootFrame.ActualWidth,
    KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 250))

Storyboard.SetTarget(swipeAnimation, listBoxItem);
Storyboard.SetTargetProperty(swipeAnimation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));

var sb = new Storyboard();

await sb.BeginAsync();

Of course, feel free to create your custom animation here. Also, the extension method BeginAsync is defined as below:

public static Task BeginAsync(this Storyboard storyboard)
    var tcs = new TaskCompletionSource<bool>();

    EventHandler completedEventHandler = null;
    completedEventHandler = (sender, o) =>
        storyboard.Completed -= completedEventHandler;
    storyboard.Completed += completedEventHandler;

    return tcs.Task;

Now, after the call to the BeginAsync method, I can redirect my user to another page:

await sb.BeginAsync();


Here is a small video of the result:


Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register

Leave a Reply