I'm thinking about how to do a color transition for a line in WPF. I'm looking for this to be as simple and succinct as possible, and also the "correct" way in the WPF world.

This is what I have, taking the line from it's previous color to Colors.LightGreen in 0.1 seconds.

Line TargetLine = GetMyTargetLine();

var s = new Storyboard(){ Duration = new Duration(TimeSpan.FromSeconds(0.1f)) };
s.Children.Add(new ColorAnimation(Colors.LightGreen, s.Duration));
Storyboard.SetTarget(s.Children[0], TargetLine);
Storyboard.SetTargetProperty(s.Children[0], new PropertyPath("Stroke.Color"));

And it is functional. Is this the proper way to do it in the WPF mindset? It just seems very clunky and verbose way to express what I want to do. Thoughts?

Edit: With Snowbear's advice I can at least get it to 4 lines. The entire context of the storyboard is right here so I don't think it's a big deal to reference the only child by index. If it were any more complex than this I'd agree that it should be a named variable.

    Line TargetLine = GetMyTargetLine();        

    var story = new Storyboard() { Children = { new ColorAnimation(color, new Duration(TimeSpan.FromSeconds(0.1))) } };
    Storyboard.SetTarget(story.Children[0], TargetLine);
    Storyboard.SetTargetProperty(story.Children[0], new PropertyPath("Stroke.Color"));
  • 1
    \$\begingroup\$ By the way I don't yet have the 150 rep to tag this properly so if anyone wants to step in it'd be appreciated. \$\endgroup\$ Jan 29 '11 at 5:39

1) I believe it is not a good practice to give variables one-letter names. Storyboard story = ...
2) I believe you can specify Duration in ColorAnimation only. And do not set it for Storyboard.
3) I would introduce variable for ColorAnimation because s.Children[0] looks weird to me when I know that it is ColorAnimation.
4) Strangely you are using 0.1f where parameter is double anyway.
5) I would consider using object and collection initializers for Storyboard.Children.
6) Optionally I would think on removing storyboard variable and start it immediatly after constructing.

Result: my code looks differently, but readability changes are subjective:

Line TargetLine = line;

var duration = new Duration(TimeSpan.FromSeconds(0.1));
var colorAnimation = new ColorAnimation(Colors.LightGreen, duration);
Storyboard.SetTarget(colorAnimation, TargetLine);
Storyboard.SetTargetProperty(colorAnimation, new PropertyPath("Stroke.Color"));

new Storyboard {Children = {colorAnimation}}.Begin();

No need for a storyboard:

var colourAnimation = new ColorAnimation(Colors.Red, new Duration(TimeSpan.FromSeconds(0.1)));
line.Stroke.ApplyAnimationClock(SolidColorBrush.ColorProperty, colourAnimation.CreateClock()); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.