Windows Phone 实用开发技巧(26):对DataTemplate中的元素播放动画

有些时候我们需要对ListBox中的某项做出一种点击动画,即点击ListBox的某项时,被点的Item播放一个相应的动画。通常,我们需要自定义ListBox的ItemTemplate以做出自定义的ListBoxItem。下面,我讲讲如何利用Expression Blend和Visual Studio 分别实现这样的效果。

一. 使用Expression Blend

1. 创建Windows Phone Databound Application

image

2. 去掉MainListBox_SelectionChanged中的事件,由于模板中代码是选中ListBox某项就进去该项的Detail Page,我们不需要,所以暂时先注释掉,如下图:

image

3. 编辑MainListBox的模板

image

4. 选择States卡片,新建一个state group

image

5. 命名为Selected,这时候注意到页面外围有一个红框,表示我们正在录制相应的State

image

6.在Objects and  Timeline中选择第一个textBlock,将其属性面板中的TranslateX设为204

image

7.切换到Assets卡片,我们对StackPanel加上相应的Behavior控制,选中GoToStateAction,拖拽至Objects and  Timeline中的StackPanel上,如下图:

image

8. 运行程序,点击某项后,第一行文字会向右运动。

说明:上述方法其实是使用State去实现相应的动画的,下面以Visual Studio编码的形式真正实现播放动画。

二、使用Visual Studio

运行效果图下图,点击ListBox中的某项后,图片会旋转180度

image

<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

posted @   Alexis  阅读(2482)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示