views:

242

answers:

1

Hi!

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 opacity. 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#?

Thanks very much!

+1  A: 

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
}
itowlson
thanks very much but could you post a snippet code in xaml about how implementing storyboard's (with repeatbehaviour to forever) with animations for opacity and foreground color? I am new in xaml, sorry.
toni
Added example -- not great style but should get you started!
itowlson
thanks very much, great example. One thing, I have heard that is possible to do a sequence of animations, for example, in this case do first the opacity animation and when it finishes then start the foreground animation. If I would want to do it, which modification I would have to do in storyboard to start foreground animation just at the end of the opacity animation (and not before or at the same time)? thanks very much.
toni
I think the simplest way is to set a BeginTime on the foreground animation so that it begins just as the opacity animation is finishing. There may be a more elegant way though, not sure. You might want to post this as a separate question (assuming it hasn't been asked already): it will get more attention and therefore better answers as its own question compared to a comment!
itowlson