【问题标题】:Run action when c# wpf animation endsc# wpf动画结束时运行动作
【发布时间】:2021-11-19 08:53:40
【问题描述】:

我正在学习 wpf 并同时使用它开发应用程序。当双重动画(或其他类型)完成时,我很难弄清楚如何运行某些东西。例如:

DoubleAnimation myanim = new DoubleAnimation();
myanim.From = 10;
myanim.To = 100;
myanim.Duration = new Duration(TimeSpan.FromSeconds(3));
myview.BeginAnimation(Button.OpacityPropert, myanim);

//Code to do something when animation ends

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace app
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        DoubleAnimation widthbutton = new DoubleAnimation();
        widthbutton.From = 55;
        widthbutton.To = 100;
        widthbutton.Duration = new Duration(TimeSpan.FromSeconds(1.5));
        button1.BeginAnimation(Button.HeightProperty, widthbutton);

        DoubleAnimation widthbutton1 = new DoubleAnimation();
        widthbutton1.From = 155;
        widthbutton1.To = 200;
        widthbutton1.Duration = new Duration(TimeSpan.FromSeconds(1.5));
        button1.BeginAnimation(Button.WidthProperty, widthbutton1);

        widthbutton.Completed += new EventHandler(myanim_Completed);
    }
    private void myanim_Completed(object sender, EventArgs e)
    {
        //your completed action here
        MessageBox.Show("Animation done!");
    }
}
}

这是如何实现的?我已经阅读了很多关于此的其他帖子,但它们都使用 xaml 进行了解释,但是我想使用 c# 代码来完成。谢谢!

【问题讨论】:

    标签: c# wpf animation doubleanimation


    【解决方案1】:

    您可以将事件处理程序附加到 DoubleAnimation 的 Completed 事件。

    myanim.Completed += new EventHandler(myanim_Completed);
    
    private void myanim_Completed(object sender, EventArgs e)
    {
        //your completed action here
    }
    

    或者,如果你更喜欢内联,你可以这样做

     myanim.Completed += (s,e) => 
         {
            //your completed action here
         };
    

    记得在开始动画之前附加处理程序,否则它不会触发。

    【讨论】:

    • 它没有显示代码中的任何错误,但是当动画结束时,什么也没有发生,请参阅我的编辑以获取完整的新代码
    • 您在附加处理程序之前开始动画。您需要先附加处理程序,然后再调用BeginAnimation
    • 啊啊,好极了。非常感谢!完美运行!
    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2020-08-23
    • 2018-11-30
    • 2010-10-30
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多