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