2011-05-06 218 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; 
    } 
}