Fade any control using a WPF animation

2019-04-30 05:36发布

I want to toggle the opacity of a control (Button, TextBox, Panel, etc) in my WPF project and wanted to check to see if I had done it correctly.

My question is: Is this the type of functionality that you’d normally write in XAML or would you use code similar to that below to achieve the fade in/fade out result?

internal static class AnimationExtensions
{
    internal enum TransitionSpeed
    {
        Instant = 0,
        Fast = 100,
        Normal = 200,
        Slow = 500
    }

    /// <summary>
    /// Toggles the opacity of a control.
    /// </summary>
    /// <param name="control">The control.</param>
    internal static void ToggleControlFade(this Control control)
    {
        control.ToggleControlFade(TransitionSpeed.Normal);
    }

    /// <summary>
    /// Toggles the opacity of a control.
    /// </summary>
    /// <param name="control">The control.</param>
    /// <param name="speed">The speed.</param>
    internal static void ToggleControlFade(this Control control, TransitionSpeed speed)
    {
        Storyboard storyboard = new Storyboard();
        TimeSpan duration = new TimeSpan(0, 0, 0, 0, (int)speed); //

        DoubleAnimation animation = new DoubleAnimation { From = 1.0, To = 0.0, Duration = new Duration(duration) };
        if (control.Opacity == 0.0)
        {
            animation = new DoubleAnimation { From = 0.0, To = 1.0, Duration = new Duration(duration) };
        }

        Storyboard.SetTargetName(animation, control.Name);
        Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity", 0));
        storyboard.Children.Add(animation);

        storyboard.Begin(control);
    }
}

As you can probably tell I’m very, very new to WPF.

Thanks

1条回答
Rolldiameter
2楼-- · 2019-04-30 06:26

I tend to find in places where I need to perform an action after an animation or where the animation is dependent on complex triggers that the code-behind is the best place, otherwise the XAML is a good place to put the animation. (I usually do this for things like transitions or simple 'onclick' sort of events.

查看更多
登录 后发表回答