2011-05-06 222 views
3

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

回答

3

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; 
    } 
}