Search code examples
c#wpfstoryboardwindowtransparency

WPF. Animation of window transparency


I need a smooth animation of window transparency. I added this code to the "LOADED" event of the window.

DoubleAnimation myDoubleAnimation = new DoubleAnimation();
            myDoubleAnimation.From = 100.0;
            myDoubleAnimation.To = 0.1;
            myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));
            Storyboard.SetTargetName(myDoubleAnimation, Name);
            Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(UIElement.OpacityProperty));
            Storyboard myStoryboard = new Storyboard();
            myStoryboard.Children.Add(myDoubleAnimation);
            myStoryboard.Begin(this);

There is a sharp jump of transparency. Animation is missing. Where there has been a mistake?


Solution

  • Opacity is a relative value in the range 0 .. 1. Use

    myDoubleAnimation.From = 1.0;
    

    or don't set it at all.

    Instead of using a Storyboard, you may also just write

    BeginAnimation(OpacityProperty, new DoubleAnimation
    {
        To = 0.1,
        Duration = TimeSpan.FromSeconds(1)
    });