有些时候咱们须要对ListBox中的某项作出一种点击动画,即点击ListBox的某项时,被点的Item播放一个相应的动画。一般,咱们须要自定义ListBox的ItemTemplate以作出自定义的ListBoxItem。下面,我讲讲如何利用Expression Blend和Visual Studio 分别实现这样的效果。 app
一. 使用Expression Blendide
1. 建立Windows Phone Databound Application动画
2. 去掉MainListBox_SelectionChanged中的事件,因为模板中代码是选中ListBox某项就进去该项的Detail Page,咱们不须要,因此暂时先注释掉,以下图:编码
3. 编辑MainListBox的模板spa
4. 选择States卡片,新建一个state grouprest
5. 命名为Selected,这时候注意到页面外围有一个红框,表示咱们正在录制相应的Statecode
6.在Objects and Timeline中选择第一个textBlock,将其属性面板中的TranslateX设为204orm
7.切换到Assets卡片,咱们对StackPanel加上相应的Behavior控制,选中GoToStateAction,拖拽至Objects and Timeline中的StackPanel上,以下图:blog
8. 运行程序,点击某项后,第一行文字会向右运动。事件
说明:上述方法实际上是使用State去实现相应的动画的,下面以Visual Studio编码的形式真正实现播放动画。
2、使用Visual Studio
运行效果图下图,点击ListBox中的某项后,图片会旋转180度
<DataTemplate x:Key="DT_ListBox"> <Button BorderThickness="0" Click="Btn_Click"> <StackPanel Orientation="Horizontal"> <Image x:Name="imgD" Height="48" Width="48" Source="/appbar.back.rest.png" RenderTransformOrigin="0.5,0.5"> <Image.RenderTransform> <CompositeTransform /> </Image.RenderTransform> </Image> <TextBlock Text="{Binding}" /> </StackPanel> <Button.Resources> <Storyboard x:Name="sb_TurnRight" Storyboard.TargetName="imgD" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.Rotation)"> <DoubleAnimation From="0" To="180" /> </Storyboard> </Button.Resources> </Button> </DataTemplate>
下面是Button的Click事件
private void Btn_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; if (btn!=null) { var sb = btn.Resources["sb_TurnRight"] as Storyboard; if (sb!=null) { sb.Begin(); } } }说明:Visual Studio的方法实际上是将StoryBoard存在模板的Resouce中,而后在代码中获取并播放,灵活性更大一些。
Expression Blend Source Code
Visual Studio Souce Code