In a Windows Phone 7 project, I’m doing a color animation on a button background, changing the color through a range. I want the animation to stop when the button is clicked, and have the button’s background color stay on the color it had when it was clicked. To this end, I have the following set:
<Button Height="72" HorizontalAlignment="Left"
Margin="135,48,0,0" Name="button1" VerticalAlignment="Top" Width="160"
Click="button1_Click">
<Button.Resources>
<Storyboard x:Name="colorStoryboard">
<!-- Animate the background color of the canvas from red to green over 4 seconds. -->
<ColorAnimation BeginTime="00:00:00" Storyboard.TargetName="button1"
Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
From="Red" To="Blue" Duration="0:0:4" />
</Storyboard>
</Button.Resources>
</Button>
The click event is coded as:
private void button1_Click(object sender, RoutedEventArgs e)
{
colorStoryboard.Pause();
Brush holdBrush = new SolidColorBrush();
holdBrush = button1.Background;
colorStoryboard.Stop();
button1.Background = holdBrush;
}
This is how I think it would work: after the storyboard.Pause() stops any further change in the color (the Stop method causes the button to go back to its default background color), I am saving the Background’s current Brush into the new Brush holdBrush, and then after doing the Stop() I attempt to restore the button’s background property to the value it had when the Pause occurred, using holdBrush.
This isn’t what is happening, however. In the code above I’ve confirmed that holdBrush has the color that the button had when the storyboard paused, but after Stop occurs, holdBrush now has the default color — actually, it has the color #FFFFFF, which is the color the button takes on when it is clicked. Any ideas, anyone?
Animation in Silverlight for Windows Phone are run by Compositor Thread and what you do is just a reference copy of Background object (shallow copy) and the value is shared between UI Thread and Compositor Thread. To get the value of color you need to get the value of a DependencyProperty
But this approach is not the best for Silverlight. I would restyle the default template of the button(Visual State).