WPF动画、故事板、事件触发器

WPF动画通过一组动画类表示,使用少数几个属性设置相关信息,如开始值、结束值以及持续时间。

WPF动画使用三种方法:线性插值、关键帧和路径:

线性插值:7个 "类型名+Animation类"  这些类使用插值动画。

关键帧:22个 "类型名+AnimationUsingKeyFrames" 这些类使用关键帧动画。

路径:3个 "类型名+AnimationUsingPath"类这类使用基于路径的动画。

在WPF动画中,最常用的动画技术是线性插值动画,可以在页面写动画代码也在后台写动画代码。

首先用后台代码写动画:

   XAMl代码:添加两个Button按钮给其中一个按钮添加点击事件Button_Click

<Grid>

        <Grid.RowDefinitions>

            <RowDefinition />

            <RowDefinition />

        </Grid.RowDefinitions>

        <Button Width="150" Height="60" Grid.Row="0" Click="Button_Click">点击开始动画</Button>

        <Button Grid.Row="1" Name="btn1" Width="150" Height="60" Content="动画"></Button>

 </Grid>

页面图:

后台代码:实例化在前面列出的其中一个动画类,然后使用修改元素的BeginAnimation()方法

private void Button_Click(object sender, RoutedEventArgs e)

        {

            //实例化一个DoubleAnimation类。

            DoubleAnimation doubleAnimation = new DoubleAnimation();

            //设置From属性。

            doubleAnimation.From = btn1.Width;

            //设置To属性。

            doubleAnimation.To = 250;

            //设置Duration属性。

            doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));

            //为元素设置BeginAnimation方法。

            btn1.BeginAnimation(Button.WidthProperty, doubleAnimation);

        }

点击“点击开始动画”按钮,执行后台动画代码,按钮“动画”的Width属性开始变化

页面写动画代码,不需要后台代码,需要“故事板”和“事件触发器”。

故事板:故事板是增强的时间线,可用来分组多个动画,而且具有控制动画播放的能力---暂停、停止以及播放位置。能够使用TargetProperty和TargetName属性指向某个特定属性和特定元素。

事件触发器:

可以在以下4个位置定义事件触发器。

1、在样式中(Style.Triggers集合):属性触发器,事件触发器。

2、在数据模板中(DataTemplate.Triggers集合)。

3、在控件模板中(ControlTemplate.Triggers集合)。

4、直接在元素中定义事件触发器(FrameworkElement.Triggers集合)。

代码:

    <Grid>

        <Button Width="200" Height="80" Content="动画 " FontSize="20">

            <Button.Triggers>

                <EventTrigger RoutedEvent="Button.Click">

                    <EventTrigger.Actions> RoutedEvent="Button.Click"

                        <BeginStoryboard>

                            <Storyboard >

                                <DoubleAnimation Storyboard.TargetProperty = "Width" To="350"  RepeatBehavior="Forever" Duration="0:0:3"></DoubleAnimation>

                            </Storyboard>

                        </BeginStoryboard>

                    </EventTrigger.Actions>

                </EventTrigger>

            </Button.Triggers>

        </Button>

  </Grid>

添加一个元素触发器,在定义触发器的事件“RoutedEvent="Button.Click"”点击事件,添加故事版在触发器内。

页面图:

 

运行效果图:点击“动画”按钮

 

猜你喜欢

转载自blog.csdn.net/weixin_44545554/article/details/89370516
今日推荐