WPF:删除动画后防止触发 "Completed"事件

标签 wpf animation

如何从 WPF 元素中删除正在运行的动画,使其不会触发其 Completed 事件?

提出的解决方案herehere删除动画的可见效果,但 Completed 事件仍会在动画完成时触发。

这里有一些代码演示了我的问题(它位于带有标签、按钮和文本框的窗口后面的代码中):

    int _count = 0;

    private void button1_Click(object sender, RoutedEventArgs e) {
        myLabel.Content = "Starting animation: " + _count++;

        // Cancel any already-running animations and return
        // the label opacity to 1.0.
        myLabel.BeginAnimation(Label.OpacityProperty, null);
        myLabel.Opacity = 1.0;

        // Create a new animation to fade out the label.
        DoubleAnimation opacityAnim = new DoubleAnimation(1.0, 0.0, TimeSpan.FromSeconds(2), FillBehavior.Stop) {
            BeginTime = TimeSpan.FromSeconds(3)
        };
        opacityAnim.Completed += (sndr, ev) => {
            myTextbox.Text += Environment.NewLine + "Completed fired.";
        };

        // Start the countdown/animation.
        myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim);
    }

如何删除动画,使其不会引发其 Completed 事件?

最佳答案

取消订阅 Completed 事件...这也意味着您必须将 Completed 事件处理程序从 lambda 重写为显式方法:

   DoubleAnimation _opacityAnim; // Created somewhere else.

   private void button1_Click(object sender, RoutedEventArgs e) 
   {
    myLabel.Content = "Starting animation: " + _count++;

    // Cancel any already-running animations and return
    // the label opacity to 1.0.
    _opacityAnim.Completed -= AnimationCompleted;

    myLabel.BeginAnimation(Label.OpacityProperty, null);
    myLabel.Opacity = 1.0;

    // Create a new animation to fade out the label.
    opacityAnim.Completed += AnimationCompleted;

    // Start the countdown/animation.
    myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim);
}

 private void AnimationCompleted(object sender, EventArgs e)
 {
        myTextbox.Text += Environment.NewLine + "Completed fired.";
 }

关于WPF:删除动画后防止触发 "Completed"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327929/

相关文章:

wpf - 在 TabControl 中调整 TabItem 标题大小

c# - 如何将 "Clear"按钮添加到 WPF 中的文本框?

c# - 如何获取WPF中任意控件的 "Content"?

c# - Scrollviewer 中的 WPF 组合框不起作用

javascript - Python-实时条形图

javascript - 提高 CSS3 动画的性能

ios - 防止 UITableView 超出单元格绑定(bind) View 在 insertRowsAtIndexPaths : 上剪辑

java - 找不到符号方法 setAnimationListener

qt - QGraphicsItem 沿着路径移动

c# - 带有按钮 "Yes to All"和 "No to All"的消息框