wp8 點擊ListBoxItem動畫

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


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 explainedhere) 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();
sb.Children.Add(swipeAnimation);
 
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;
        tcs.TrySetResult(true);
    };
    storyboard.Completed += completedEventHandler;
    storyboard.Begin();
 
    return tcs.Task;
}

Now, after the call to the BeginAsync method, I can redirect my user to another page:
await sb.BeginAsync();
 
this.NavigationService.GoToQuestionsPage(selectedCategory.Id);

效果,點擊向右飛出。



From:http://blog.thomaslebrun.net/2014/01/windows-phone-8-start-an-animation-on-the-selected-listboxitem-during-listbox-selectionchange-event/#.Ute_PBBOVo7



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章