【问题标题】:wp7 / Silverlight] How to animate a ListBoxItem on SelectionChanged?wp7 / Silverlight] 如何在 SelectionChanged 上为 ListBoxItem 设置动画?
【发布时间】:2010-10-25 16:17:16
【问题描述】:
我正在开发一个应用程序(VisualStudio 2010 Express for Windows Phone)。
我有一个带有图像的列表框和一个带有动画(投影)的情节提要,当 SelectionChanged 事件被触发时(不是立即,而是在事件处理程序中),我想将其应用于特定的列表框项/图像。
如何将我的动画“链接”到这个特定的 ListBoxItem?
【问题讨论】:
标签:
silverlight
windows-phone-7
【解决方案1】:
好吧,在尝试和错误之后,我想出了一个解决方案,但这并不是我想要的(故事板在数据模板之外定义,可能代码更少。我认为仅翻转图像太多了),但非常接近.
所以,示例列表框:
<ListBox x:Name="lbxCardTable" SelectionChanged="lbxCardTable_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="imgContainer">
<Image x:Name="img" Source="{Binding } />
<Grid.Resources>
<Storyboard x:Name="itemSb">
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName="imgContainer"
Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="90"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<Grid.Projection>
<PlaneProjection/>
</Grid.Projection>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以及背后的代码:
private void lbxCardTable_SelectionChanged(object sender, SelectionChangedEventArgs e) {
object selectedItem = lbxCardTable.SelectedItem;
ListBoxItem lbitem = (ListBoxItem)lbxCardTable.ItemContainerGenerator.ContainerFromItem(selectedItem);
var border =(Border) VisualTreeHelper.GetChild(lbitem, 0);
var mcontentcontrol =(ContentControl) VisualTreeHelper.GetChild(border, 0);
var contentpresenter =(ContentPresenter) VisualTreeHelper.GetChild(mcontentcontrol, 0);
var mgrid=(Grid)VisualTreeHelper.GetChild(contentpresenter,0);
Storyboard sb = mgrid.Resources["itemSb"] as Storyboard;
if (sb.GetCurrentState() != ClockState.Stopped) {
sb.Stop();
}
sb.Begin();
}