Animating LinearGradientBrush Color in Code-Behind

1.5k views Asked by At

I am playing a bit with trying to animate a LinearGradientBrush (lgb) in a Silverlight app. I have the following code in the constructor for my Page:

    for (int stops = 0; stops < numStops; stops++)
    {
        ColorAnimation animation = new ColorAnimation();
        animation.To =
            Color.FromArgb(255, (byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256));
        animation.Duration = TimeSpan.FromSeconds(1);
        Storyboard.SetTarget(animation, lgb);
        Storyboard.SetTargetProperty(animation,
            new PropertyPath("GradientStops[" + stops.ToString() + "].Color"));
        Storyboard story = new Storyboard();
        story.Children.Add(animation);
        story.Begin();
    }

It compiles and runs, but doesn't change the color. I just don't see what I'm doing incorrectly.

Thanks,
wTs

1

There are 1 answers

2
AnthonyWJones On BEST ANSWER

You code works fine under Silverlight 4 and in Windows Phone 7 (WP7 is pretty much Silverlight 3). My guess is if I build an isolated app for SL3 it would work there too.

The only thing missing from your code is how lgb is aquired in the first place? Are you sure its the same instance that is actually being used in your UI.

For example, I just added the brush to my LayoutRoot Grid like this:-

<Grid x:Name="LayoutRoot">
    <Grid.Background>
        <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
            <GradientStop Color="Black" Offset="0" />
            <GradientStop Color="White" Offset="1" />
        </LinearGradientBrush>
    </Grid.Background>

Then in code I assign lgb with:-

LinearGradientBrush lgb = (LinearGradientBrush)LayoutRoot.Background;