Search code examples
c#wpfstoryboardopacitydoubleanimation

WPF MediaElement Opacity is not set after executing Storyline


I'm using DoubleAnimation and Storyboard to control Opacity of MediaElement. The animation itself works fine, but if I call Disappear and playVid after several seconds, the Opacity of the player remains 0! What's the problem?

public void playVid(string source, bool isMainVid)
{
    player.Opacity = 1;
    player.Play(); //player.Opacity is 0 here!
}

public void Disappear()
{
    DoubleAnimation fadeOut = new DoubleAnimation
    {
        To = 0,
        Duration = new Duration(TimeSpan.FromMilliseconds(1000))
    };
    fadeOut.Completed += (s, e) =>
    {
        player.Stop();
    };
    var storyboard = new Storyboard();
    storyboard.Children.Add(fadeOut);
    Storyboard.SetTargetName(fadeOut, player.Name);
    Storyboard.SetTargetProperty(fadeOut, new PropertyPath(OpacityProperty));
    storyboard.Begin(mainGrid, HandoffBehavior.SnapshotAndReplace); //mainGrid is player's parent
}

Solution

  • Use FillBehavior equal to Stop, but also set the Opacity of your player to the final opacity value (in the Completed handler). Otherwise, it will be reset to its value before the animation.

    var fadeOut = new DoubleAnimation
    {
        To = 0,
        Duration = new Duration(TimeSpan.FromMilliseconds(1000)),
        FillBehavior = FillBehavior.Stop
    };
    
    fadeOut.Completed += (s, e) =>
    {
        player.Stop();
        player.Opacity = 0;
    };
    

    See this post for other approaches.