XAML Heartbeat Animation - How to ensure heart beats at least twice

℡╲_俬逩灬. 提交于 2019-12-04 20:26:33

I think you're gonna have to specify RepeatBehavior="2x" and subscribe to the Completed event for the StoryBoard and if IsHeartBeating is still true then you restart it.

<Image Height="60" Width="60" Margin="0,6,6,6"   
       Name="Heartbeat" Source="/Resources/Heartbeat.png"   
       VerticalAlignment="Bottom" HorizontalAlignment="Right"    
       Opacity=".05" Stretch="UniformToFill">
    <Image.Resources>
        <Storyboard x:Key="HeartbeatStoryboard2x"
                    RepeatBehavior="2x"
                    Completed="Storyboard_Completed">
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
                             Storyboard.Target="{Binding ElementName=Heartbeat}"
                             From="0.05" To="0.8" Duration="0:0:0.500">
            </DoubleAnimation>
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
                             Storyboard.Target="{Binding ElementName=Heartbeat}"
                             From="0.8" To="0.05" Duration="0:0:1.500">
                <DoubleAnimation.EasingFunction>
                    <PowerEase EasingMode="EaseOut" Power="6" />
                </DoubleAnimation.EasingFunction>
            </DoubleAnimation>
        </Storyboard>
    </Image.Resources>
    <Image.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHeartBeating}" Value="True">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard Name="HeartbeatStoryboard">
                            <StaticResource ResourceKey="HeartbeatStoryboard2x"/>
                        </BeginStoryboard>
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

Code behind event handler.
Update
Added boolean flag to only Stop the Storyboard when is has been re-started

private bool m_restartedAnimation = false;
private void Storyboard_Completed(object sender, EventArgs e)
{
    ClockGroup clockGroup = sender as ClockGroup;
    Storyboard heartbeatStoryboard = clockGroup.Timeline as Storyboard;
    if (IsHeartBeating == true)
    {
        m_restartedAnimation = true;
        heartbeatStoryboard.Begin();
    }
    else
    {
        if (m_restartedAnimation == true)
        {
            heartbeatStoryboard.Stop();
        }
        m_restartedAnimation = false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!