【问题标题】:WPF Storyboard event not firingWPF 故事板事件未触发
【发布时间】:2011-05-08 15:28:31
【问题描述】:

我有一个简单的故事板,它可以重复和自动反转。当它到达终点并自动反转时,我想在后面的代码中触发一个事件。重复时也是如此。我怎样才能做到这一点?最终,我在这两个事件中播放了一个 wav 文件。谢谢。

【问题讨论】:

    标签: wpf storyboard


    【解决方案1】:

    WPF 动画由 AnimationClock 控制(有点像花哨的计时器)。 AnimationClock 有一个名为 CurrentProgress 的属性,范围从 0 到 1;其中0是起点,1是终点。重复的故事板会逐渐将 CurrentProgress 从 0 变为 1 到 0 到 1...

    当 AnimationClock 指示 Animation 渲染其下一帧时,Animation 会引发其 CurrentTimeInvalidated 事件。此事件的发送者参数是 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多