Stop / start storyboard animation based on Visibility

Chris picture Chris · Jul 10, 2013 · Viewed 11.2k times · Source

I have an animation that currently starts when a Control is loaded (the animation is essentially a waiting spinner, that is applied to an empty ContentControl).

The animation however will constantly spin taking up resources. What I'd like is for the animation to start / stop based on whether the animation control is visible or not, is this possible?

<Canvas.Triggers>
    <EventTrigger RoutedEvent="ContentControl.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                Storyboard.TargetName="SpinnerRotate"
                Storyboard.TargetProperty="Angle"
                From="0" To="360" Duration="0:0:01.3"
                RepeatBehavior="Forever" />
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Canvas.Triggers>

I must have this working for both Silverlight and WPF.

Answer

Richard E picture Richard E · Jul 10, 2013

I have created an example of spinning an Ellipse based on the Visibility property. Perhaps you can use something from this.

 <Canvas>
    <Ellipse x:Name="Circle" Width="30" Height="30"
             Canvas.Left="50"
             Canvas.Top="50">
        <Ellipse.Fill>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="White" Offset="1"/>
            </LinearGradientBrush>
        </Ellipse.Fill>
        <Ellipse.RenderTransform>
            <RotateTransform x:Name="SpinnerRotate" CenterX="15" CenterY="15"/>
        </Ellipse.RenderTransform>
        <Ellipse.Style>
            <Style TargetType="Ellipse">
                <Style.Triggers>
                    <Trigger Property="Visibility" Value="Visible">
                        <Trigger.EnterActions>
                            <BeginStoryboard x:Name="SpinStoryboard">
                                <Storyboard >
                                    <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Angle"
                                                     From="0" To="360" Duration="0:0:01.3"
                                                     RepeatBehavior="Forever" />
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                        <Trigger.ExitActions>
                            <StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
                        </Trigger.ExitActions>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Ellipse.Style>
    </Ellipse>
</Canvas>