WPF Stop Storyboard on Visibility Changed

storyboard, triggers, visibility, wpf, xaml

Solution

You may do it using a control template:

<ControlTemplate>
    ... Control stuff here

    <ControlTemplate.Triggers>
        <Trigger Property="Visibility" Value="Visible">
            <Trigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource AnimationStoryboard}" x:Name="AnimationBeginStoryboard"/>
            </Trigger.EnterActions>
            <Trigger.ExitActions>
                <RemoveStoryboard BeginStoryboardName="AnimationBeginStoryboard"/>
            </Trigger.ExitActions>
        </Trigger>
    </ControlTemplate.Triggers>

</ControlTemplate>

Problem

I have a UserControl with a story board and I want to stop the animation when the control's Visibility changes. I created a Trigger to pause the animation and start it depending on the state, but I keep getting an ArgumentException. Here is the XAML: ``` <UserControl.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard x:Name="ProgressAnimation_BeginStoryboard" Storyboard="{StaticResource ProgressAnimation}"/> </EventTrigger> <Trigger Property="Control.Visibility" Value="Collapsed"> <PauseStoryboard BeginStoryboardName="ProgressAnimation_BeginStoryboard" /> </Trigger> <Trigger Property="Control.Visibility" Value="Visible"> <ResumeStoryboard BeginStoryboardName="ProgressAnimation_BeginStoryboard" /> </Trigger> </UserControl.Triggers> ``` and here is the Exception: The value "System.Windows.Media.Animation.PauseStoryboard" is not of type "System.Windows.SetterBase" and cannot be used in this generic collection. Parameter name: value How would I do this in XAML ? Thanks, Raul

Original source