WPF动画基础

前端代码

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="btn1" Content="执行动画" Width="100" Height="40" Click="btn1_Click"/>
    </Grid>
</Window>

后端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btn1_Click(object sender, RoutedEventArgs e)
        {
            //创建一个双精度的动画
            DoubleAnimation doubleAnimation = new DoubleAnimation();
            doubleAnimation.From = btn1.Width;//设置动画的初始值
            doubleAnimation.To = btn1.Width - 30;//设置动画的结束值
            doubleAnimation.Duration = TimeSpan.FromSeconds(2);//设置动画的持续时间
            doubleAnimation.AutoReverse = true;//设置是否往返
            doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;  //new RepeatBehavior(5) //执行周期

            //在当前按钮上执行动画
            btn1.BeginAnimation(Button.WidthProperty, doubleAnimation);
        }
    }
}
posted @ 2022-04-18 13:06  hack747  阅读(25)  评论(0编辑  收藏  举报