WPF:动画后将网格可见性切换回第一状态(崩溃)

时间:2018-07-10 15:12:29

标签: wpf animation grid storyboard

所以我有这个Grid

<Grid x:Name="notificarionGrid" Visibility="Collapsed"/>

我想通过动画更改其“可见性”值,所以我有以下2个故事板:

<Storyboard x:Key="fadeIn">
            <ObjectAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Visibility">
                <DiscreteObjectKeyFrame KeyTime="0">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
            <DoubleAnimation BeginTime="0:0:0.0" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:2.0"/>
        </Storyboard>

<Storyboard x:Key="fadeOut">
            <DoubleAnimation BeginTime="0:0:0:0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2.0"/>
        </Storyboard>

现在此代码可以正常工作,但是这里唯一的问题是,在fadeOut之后,我的Grid Visibility变成了Hidden而不是Collapsed,这导致某些元素在此情况下不负责任Grid

任何想法如何将我的Grid再次切换为Collapsed吗?

2 个答案:

答案 0 :(得分:1)

您可以为Completed处理Storyboard事件:

private void Storyboard_Completed(object sender, EventArgs e)
{
    notificarionGrid.Visibility = Visibility.Collapsed;
}

XAML:

<Storyboard x:Key="fadeOut" Completed="Storyboard_Completed">
    <DoubleAnimation BeginTime="0:0:0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2.0"/>
</Storyboard>

或在您的ObjectAnimationUsingKeyFrames中添加Storyboard

<Storyboard x:Key="fadeOut">
    <DoubleAnimation BeginTime="0:0:0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2.0"/>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:2" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Collapsed</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>

答案 1 :(得分:0)

使用适当的BeginTime添加另一个ObjectAnimationUsingKeyFrames以提高可见性:

<Storyboard x:Key="fadeOut">
    <DoubleAnimation Storyboard.TargetProperty="Opacity"
                     To="0" Duration="0:0:2"/>

    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility"
                                   BeginTime="0:0:2">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Collapsed</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>