c# wpf动画结束时运行操作

relj7zay  于 2022-11-18  发布在  C#
关注(0)|答案(1)|浏览(388)

我正在学习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#代码。谢谢!

mlnl4t2r

mlnl4t2r1#

您可以将事件行程常式附加至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
     };

请记住在启动动画之前附加处理程序,否则将不会触发。

相关问题