6
votes

Can anyone help me trying to find out why this doesn't work.

The brushes variable contains a pre-filled list of brushes. If I try to apply the BeginAnimation directly during the iteration, it works fine. But has a great overhead starting each animation separately...

So I was trying to put all the animations in a single storyboard, and fire them all at once...

var storyBoard = new Storyboard();           
var duration = new Duration(TimeSpan.FromMilliseconds(time));
foreach (Brush brush in brushes) 
{
    var animation = new DoubleAnimation(toValue, duration);

    storyBoard.Children.Add(animation);

    Storyboard.SetTargetProperty(animation, new PropertyPath(Brush.OpacityProperty));
    Storyboard.SetTarget(animation, brush);
}

storyBoard.Begin();

This code simply does nothing (that I can see...).

Edit: Still not sure of what is problem with the SetTarget method, either a bug or I'm just not using as it should be. Anyway I solved the problem generating unique names for my brushes at runtime and using the SetTargetName method.

1
Shouldn't you be pathing to the property that contains the brush and then the brush opacity? Something like new PropertyPath("(Shape.Fill).(SolidColorBrush.Opacity)") and then you'd see something closer to StoryBoard.SetTarget(animation, this) on the next line? I'm a beginner at best but this seems to be part of the problem. You want to change the brush of a property on an object, not the brush itself as the target (which I think you can't do anyway)Marc

1 Answers

2
votes

Try to use Storyboard.SettargetName method instead of Storyboard.SetTarget. I prepared working sample for you:

var brushes = new string[] { "br1", "br2", "br3" };
var sb = new Storyboard();
var dur = new Duration(TimeSpan.FromMilliseconds(500.0));
double toValue = 1.0;

foreach (var brush in brushes)
{
  var anim = new DoubleAnimation(toValue, dur);
  Storyboard.SetTargetName(anim, brush);
  Storyboard.SetTargetProperty(anim, new PropertyPath("(0)", new DependencyProperty[] { Brush.OpacityProperty }));
  sb.Children.Add(anim);
}         

sb.Begin(this);

Remember, that in this case you also should set a Namescope as parameter for Storyboard.Begin method.

See also: Another answers on the Stackoverflow.