开发者

WPF - Opacity property doesn't work the second time

开发者 https://www.devze.com 2023-02-09 14:22 出处:网络
I have the following code: // Fade out the photo, and after, fade in canvas double DurationSeconds = duration.TimeSpan.TotalSeconds;

I have the following code:

    // Fade out the photo, and after, fade in canvas
double DurationSeconds = duration.TimeSpan.TotalSeconds;

System.Windows.Media.Animation.Storyboard storyboard = new System.Windows.Media.Animation.Storyboard();

System.Windows.Media.Animation.DoubleAnimation animScreenshot = new System.Windows.Media.Animation.DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(DurationSeconds / 3)));
System.Windows.Media.Animation.Storyboard.SetTargetName(animScreenshot, DrawingCanvasTransition.Name);
System.Windows.Media.Animation.Storyboard.SetTargetProperty(animScreenshot, new PropertyPath(Image.OpacityProperty));

// !!!
RectangleTransition.Opacity = 1; // <----------------- PROBLEM IS HERE
RectangleTransition.UpdateLayout();

System.Windows.Media.Animation.DoubleAnimation animRect = new System.Windows.Media.Animation.DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(DurationSeconds / 3)));
animRect.BeginTime = TimeSpan.FromSeconds( DurationSeconds * .66);
System.Windows.Media.Animation开发者_开发知识库.Storyboard.SetTargetName(animRect, RectangleTransition.Name);
System.Windows.Media.Animation.Storyboard.SetTargetProperty(animRect, new PropertyPath(Rectangle.OpacityProperty));

storyboard.Children.Add(animScreenshot);
storyboard.Children.Add(animRect);

// And start!
storyboard.Begin(this);

The problem is that the first time the function is called, the animation works perfectly. The second time, the opacity property doesn't change at all. What could be the problem? In the debugger, the .Opacity property = 0 even after the line where it should change to 1. The animations do however work.


Aside from setting FillBehavior to Stop, as you mentioned there are a couple of other ways to make sure this property locking doesn't happen:

  • Remove the animation object by handling the animation's Completed event. (e.g., "storyboard.Remove(myObject)")
  • Make the animation reversible by setting the AutoReverse (obviously this doesn't work if you want the end result to be different from how you started).

This is actually a very common source of confusion and MSDN has a decent-sized writeup on this topic.


Compare the answer to this question.
You should change the opacity again via an animation or somehow disable your animation.

0

精彩评论

暂无评论...
验证码 换一张
取 消