当C# WPF动画结束时运行操作

14

我正在学习WPF并同时用它开发一个应用程序。我很难弄清楚当DoubleAnimation(或其他类型)完成时如何运行某些内容。例如:

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#代码来完成。感谢!

1个回答

37

您可以将事件处理程序附加到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
     };

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


代码中没有显示任何错误,但是当动画完成后,什么也没有发生,请查看我的编辑以获取完整的新代码。 - user1446632
9
在附加处理程序之前启动动画。在调用BeginAnimation之前,您需要先附加处理程序。 - keyboardP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接