I have a WPF window with a label control used for messages to the user. After a few seconds, I want the message to fade away. I have created a DispatcherTimer
Its due to the "fill behavior" of the animation. It's effectively holding on to the value after the animation and not letting go, preventing it from being updated.
Its an easy fix, change the fill behavior to stop and add an event handler to change the opacity value to 0 after the animation (otherwise it will go back to 1)
animation.FillBehavior = FillBehavior.Stop;
animation.Completed += delegate
{
lblTest.Opacity = 0;
};
I have tested this with your code and it worked.
Ben
By default, an animation's FillBehavior
is set to HoldEnd
, which means that the animation holds the final value of the target property. If you want to reset the value later, you either need to remove the animation, or you set the FillBehavior to Stop
. You could then add a handler for the animation's Completed
event to keep the final value manually.
Note also that you don't need a timer to delay the start of the animation. You may set its BeginTime
property instead.
Finally, no Storyboard is needed to animate a single property. You could call UIElement.BeginAnimation
instead.
private void btnChangeLabel_Click(object sender, RoutedEventArgs e)
{
var animation = new DoubleAnimation
{
To = 0,
BeginTime = TimeSpan.FromSeconds(5),
Duration = TimeSpan.FromSeconds(2),
FillBehavior = FillBehavior.Stop
};
animation.Completed += (s, a) => lblTest.Opacity = 0;
lblTest.BeginAnimation(UIElement.OpacityProperty, animation);
}
private void btnResetOpacity_Click(object sender, RoutedEventArgs e)
{
lblTest.Opacity = 1;
}