WPF故事板事件未触发。

3

我有一个简单的剧情板,它是重复和自动反转的。当它到达结尾并自动反转时,我想在代码后台中触发一个事件。重复时也是如此。我该怎么做?最终,我在这两个事件期间播放了一个wav文件。谢谢。

1个回答

3
WPF动画由AnimationClock(类似于高级定时器)控制。AnimationClock有一个名为CurrentProgress的属性,范围从0到1;其中0是起点,1是终点。重复的storyboard将逐渐将CurrentProgress从0变为1,再从1变为0...
当AnimationClock指示Animation呈现其下一帧时,Animation会引发其CurrentTimeInvalidated事件。此事件的sender参数是AnimationClock。您可以在此时检查CurrentProgress。但是,由于此事件仅在绘制新帧时触发,因此CurrentProgress可能永远不会完全为0或完全为1。相反,您需要寻找趋势。当您看到趋势改变时,意味着循环已开始或已反转。
示例xaml:
<Grid x:Name="uxGrid" Background="White">
    <Grid.Triggers>
        <EventTrigger RoutedEvent="Grid.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetName="uxGrid" Changed="ColorAnimation_Changed" CurrentTimeInvalidated="ColorAnimation_CurrentTimeInvalidated"  Storyboard.TargetProperty="Background.Color" From="Blue" To="Green" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Grid.Triggers>
</Grid>

示例代码:

private double? _clockLastProgress;  // Tracks Trend
private bool    _clockLastDecreased; // Tracks Trend Direction

private void ColorAnimation_CurrentTimeInvalidated(object sender, EventArgs e)
{
    AnimationClock clock = sender as AnimationClock;

    if (clock != null && clock.CurrentProgress.HasValue)
    {
        if (!_clockLastProgress.HasValue)
        {
            // Your Code Here
        }
        else
        {
            if (_clockLastDecreased)
            {
                if (clock.CurrentProgress > _clockLastProgress)
                {
                    // Your Code Here
                    _clockLastDecreased = false;
                }
            }
            else
            {
                if (clock.CurrentProgress < _clockLastProgress)
                {
                    // Your Code Here
                    _clockLastDecreased = true;
                }
            }
        }

        _clockLastProgress = clock.CurrentProgress.Value;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接