WPF Stop Storyboard on Visibility Changed

20,839

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>
Share:
20,839
HaxElit
Author by

HaxElit

Updated on July 21, 2022

Comments

  • HaxElit
    HaxElit almost 2 years

    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

  • HaxElit
    HaxElit over 14 years
    That won't work because a UserControl can only contain EventTriggers while I need a <Trigger>.
  • qakmak
    qakmak almost 6 years
    This is not a good solution for the question, because use this way can't pause and resume the animation.