问题
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?
回答1:
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>
回答2:
Visibiltiy
is a discrete value - it's either on or off, so animating will still result in a sudden disappearance rather than a gradual fading out. You could instead animate the Opacity
of the StackPanel
from 1 to 0, and then animate the Visibilty
to Hidden
(or Collapsed
) after that.
来源:https://stackoverflow.com/questions/7685364/wpf-stackpanel-visibility-animation