Search code examples
c#.netvisual-studiocoloranimation

.NET - ColorAnimation doesn't work


I created a ColorAnimation for a SpotLight-object, but it doesn't seem to work. What am I doing wrong?

ColorAnimation mouseEnterColorAnimation = new ColorAnimation();
mouseEnterColorAnimation.To = Colors.Red;
mouseEnterColorAnimation.Duration = TimeSpan.FromSeconds(5);
Storyboard.SetTargetName(mouseEnterColorAnimation, "MyAnimatedBrush");

Storyboard.SetTargetProperty(mouseEnterColorAnimation, new PropertyPath(SpotLightAuditorium.Color));
Storyboard storyboard = new Storyboard();
storyboard.RepeatBehavior = RepeatBehavior.Forever;
storyboard.Children.Add(mouseEnterColorAnimation);
storyboard.Begin(this);

Solution

  • When using Storyboard.SetTargetName, the name must be the value of the actual Name property of the FrameworkElement instance where you want to animate a property. So in your case probably an instance of the SpotLightAuditorium control:

    Storyboard.SetTargetName(mouseEnterColorAnimation, mySpotlightAuditorium.Name);
    

    The propertypath must be a reference to an actual dependency property:

    Storyboard.SetTargetProperty(mouseEnterColorAnimation, new PropertyPath(SpotLightAuditorium.ColorProperty));
    

    If you want to animate a Brush directly (wich doesn't have a Name property) you have to register the name of the brush in the current Page/UserControl/Window using RegisterName This the same as using XAML x:Name.

    ALternativlely you can use the following approach for elements that derive from Animatable:

    ColorAnimation mouseEnterColorAnimation = new ColorAnimation();
    mouseEnterColorAnimation.To = Colors.Red;
    mouseEnterColorAnimation.Duration = TimeSpan.FromSeconds(5);
    myAnimatedBrush.BeginAnimation(SolidColorBrush.ColorProperty, null); // remove the old animation to prevent memoryleak
    myAnimatedBrush.BeginAnimation(SolidColorBrush.ColorProperty, mouseEnterColorAnimation);