如何在代码中的淡入淡出动画上设置BeginTime?

时间:2018-10-04 15:28:44

标签: wpf wpf-animation

我从this post下无耻地复制了XAML。我在显示信息消息或错误消息的消息控件中使用它。

如果该消息是“ INFO”,我希望它在屏幕上消失10秒钟,然后消失。如果消息是错误,我希望它在屏幕上停留30秒钟。

问题在于消息总是在10秒后消失。

我能够找到this similar question,但是这是一个不同的问题,或者我不明白答案。

构造函数:

public MessageControl()
{
    InitializeComponent();
    ErrorMessageVisibility = Visibility.Collapsed;
    InfoMessageVisibility = Visibility.Collapsed;
    ErrorMessageDelay = TimeSpan.FromSeconds(30);
    InfoMessageDelay = TimeSpan.FromSeconds(10);

}

从依赖项属性调用:

private static void SetMessage(MessageControl thisControl, string msg, bool isError)
{
    if (settingMessage)
        return; // prevent recursion

    settingMessage = true;
    thisControl.ErrorMessage = isError? msg : null;
    thisControl.InfoMessage = !isError ? msg : null;
    thisControl.ErrorMessageVisibility = string.IsNullOrEmpty(thisControl.ErrorMessage) ? Visibility.Collapsed : Visibility.Visible;
    thisControl.InfoMessageVisibility = string.IsNullOrEmpty(thisControl.InfoMessage) ? Visibility.Collapsed : Visibility.Visible;
    Storyboard sb = ((Storyboard)thisControl.FindResource("FadeOut"));

    if (thisControl.ErrorMessageVisibility == Visibility.Visible)
    {
        sb.Children[2].BeginTime = thisControl.ErrorMessageDelay;
        sb.Begin(thisControl.ErrorMessageBorder);
    }
    else if (thisControl.InfoMessageVisibility == Visibility.Visible)
    {
        sb.Children[2].BeginTime = thisControl.InfoMessageDelay;
        sb.Begin(thisControl.InfoMessageBorder);
    }

    settingMessage = false;
}

XAML:

<Storyboard x:Key="FadeOut" Duration="0:1:0:0">
    <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:0.2"/>
    <DoubleAnimation BeginTime="0:0:5:0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:5.5" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Hidden</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>

0 个答案:

没有答案