在 wpf 中启动后停止故事板

Stop a storyboard after starting in wpf

我使用 Storyboard 来让 Image 闪烁。我已经在 XAML:

上定义了故事板
<UserControl.Resources>
    <Storyboard x:Key="AnimateFlicker" RepeatBehavior="Forever">
        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                 From="0"
                 To="1"
                 AutoReverse="True"
                 BeginTime="0:0:1"
                 Duration="0:0:0.08" />
        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                 From="1"
                 To="1"
                 AutoReverse="True"
                 Duration="0:0:0.4" />
        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                 From="1"
                 To="0"
                 AutoReverse="True"
                 Duration="0:0:0.08" />
    </Storyboard>
</UserControl.Resources>

在我的代码中,我使用了这段代码来启动故事板:

private void Blink(bool blink)
    {

        Storyboard storyboard = TryFindResource("AnimateFlicker") as Storyboard;
        if (blink)
        {
            if (storyboard != null)
            {
                imgState.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
            }
        }
        else
        {
            storyboard.Stop(); //this line wont work and blinking continues.
        }
    }

但是正如我在我的代码中提到的那样 storyboard.Stop() 不起作用并且继续闪烁。启动后如何停止闪烁?

调用 Storyboard.Begin,然后调用 Storyboard.PauseStoryboard.Pause,具体取决于您是否希望动画目标 属性 仍然受到影响:

private void Blink(bool blink)
{
    Storyboard storyboard = TryFindResource("AnimateFlicker") as Storyboard;
    if (blink)
    {
        if (storyboard != null)
        {
            storyboard.Begin(imgState, HandoffBehavior.SnapshotAndReplace, true);
        }
    }
    else
    {
        storyboard.Pause(imgState);
    }
}