In WPF, how can I do animation until background worker finishes its work?
I have an application that do some hard stuff when user clicks a start button and takes a long time. During this I would like to do some animation over a label, for example, changing opacity from 0 to 1 and vice versa and change foreground color between several colors at the same time changing opa开发者_运维技巧city. I want it stops doing animation when background worker finishes its work. How can I do this? and how can I start animation and stop it from c#?
Your animations will be hosted in a Storyboard.
- To make the animations run indefinitely, set the Storyboard's RepeatBehavior to Forever.
- To start the animations when you kick off the BackgroundWorker, call the Storyboard.Begin method.
- To stop the animations when the BackgroundWorker finishes, in your RunWorkerCompleted event handler, call the Storyboard.Stop method.
Here's an example:
<Window.Resources>
<Storyboard x:Key="sb" Duration="0:0:2" RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetName="l"
Storyboard.TargetProperty="Opacity"
From="1" To="0" AutoReverse="True" />
<ColorAnimation Storyboard.TargetName="l"
Storyboard.TargetProperty="Foreground.Color"
From="HotPink" To="Lime" AutoReverse="True" />
</Storyboard>
</Window.Resources>
<StackPanel>
<Label Name="l" FontSize="72">Oh noes!</Label>
<Button Click="Button_Click">Animate me!</Button>
</StackPanel>
And the Button_Click handler:
private void Button_Click(object sender, RoutedEventArgs e)
{
((Storyboard)(FindResource("sb"))).Begin();
// and kick off your BackgroundWorker
}
精彩评论