I want to toggle the opacity of a control (Button, TextBox, Panel, etc) in my WPF project and wanted to check to开发者_JAVA百科 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
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.
精彩评论