WPF stackpanel visibility animation

hikizume picture hikizume · Oct 7, 2011 · Viewed 7.5k times · Source

I have a stackpanel with a button which, when clicked, makes the stackpanel disappear. I want to animate the transition form visible to hidden, but haven't been able to.

I looked around for a while and bumped into something that looks like this:

<StackPanel Margin="80,60,60,80" Background="Gray">
    <StackPanel.Triggers >

        <EventTrigger  > 
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard TargetProperty="Visibility">

                        <DoubleAnimation Duration="0:0:5:0" From="Visible" To="Hidden"/>

                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>

    </StackPanel.Triggers>
    <Button Name="buttonTop" Content="TOP" Margin="40,40,40,40" Click="buttonTop_Click" Width="131" />
</StackPanel>

which of course, is not 100% there yet. Any ideas?

Answer

AkselK picture AkselK · Oct 7, 2011

You can use

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ItemsHost"
                               Storyboard.TargetProperty="Visibility">
    <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>

This is pretty much a setter in a storyboard, where KeyTime describes the time when the value should be set. So the full storyboard would be like this:

<BeginStoryboard>
    <Storyboard>
        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                         To="0" Duration="0:0:5.0"/>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
            <DiscreteObjectKeyFrame KeyTime="0:0:5.0" Value="{x:Static Visibility.Hidden}"/>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</BeginStoryboard>

edit: How to make the storyboard trigger when button is clicked:

<Button Content="Button" HorizontalAlignment="Left" Margin="337,221,0,0" VerticalAlignment="Top" Width="75">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetProperty="Opacity"
                 To="0" Duration="0:0:5.0"/>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                        <DiscreteObjectKeyFrame KeyTime="0:0:5.0" Value="{x:Static Visibility.Hidden}"/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>