2013-12-11 37 views
1

我一直在尋找一種方法,以便用相同的動畫多次動畫一個對象。我有一個文本塊,我想沿着Y軸向下移動一定的數量,我希望它保持在那裏。後來我想用相同的動畫將文本塊進一步向下移動到Y軸上。到目前爲止,每當我嘗試這個時,它都會將文本塊恢復到原始位置,然後對其進行動畫處理。我環顧四周,並沒有真正看到任何與我有關的問題,所以我想我會問自己的問題。這是播放動畫的方法。wpf - 在同一控件上覆制動畫

private void Anim_TextBlocks() 
    { 
     foreach (TextBlock aBlock in theTextBlocks) 
     {  
      var tg = new TransformGroup(); 
      var translation = new TranslateTransform(30, 0); 
      var translationName = "t" + translation.GetHashCode(); 
      RegisterName(translationName, translation); 
      tg.Children.Add(translation); 
      aBlock.RenderTransform = tg; 
      var anim = new DoubleAnimation(); 
      anim.By = 100; 
      anim.Duration = TimeSpan.FromSeconds(3); 
      anim.EasingFunction = new PowerEase { EasingMode = EasingMode.EaseOut }; 

      var story = new Storyboard(); 
      Storyboard.SetTargetName(story, translationName); 
      Storyboard.SetTargetProperty(story, new PropertyPath(TranslateTransform.YProperty)); 
      var storyboardName = "s" + story.GetHashCode(); 
      Resources.Add(storyboardName, story); 
      story.Children.Add(anim); 

      story.Completed += delegate 
      { 
       if (queue.Count != 0) 
        Create_TextBlock(this, null); 
       else 
        button1.Content = "off"; 
      }; 
      this.BeginStoryboard(story, HandoffBehavior.Compose, true); 
      button1.Content = "on"; 
     } 
    } 

感謝您的幫助!

+0

DispatcherTimer可能有助於爲N次動畫... –

回答

0

原來,每次重新創建TranslateTransform都讓我的文本塊從原始位置開始。進行必要的更改後,我的代碼現在可以正常工作,如下所示:

foreach (TextBlock aBlock in theTextBlocks) 
    { 
    // Check for existing TranslateTransform 
    var translation = aBlock.RenderTransform as TranslateTransform; 
    if (translation == null) 
    { 
     aBlock.RenderTransform = new TranslateTransform(30, 0); 
    } 
    translation = aBlock.RenderTransform as TranslateTransform; 
    var anim = new DoubleAnimation(); 
    anim.By = 100; 
    anim.Duration = TimeSpan.FromSeconds(3); 
    anim.EasingFunction = new PowerEase { EasingMode = EasingMode.EaseOut }; 

    anim.Completed += delegate 
    { 
     if (queue.Count != 0) 
     Create_TextBlock(this, null); 
     else 
     button1.Content = "off"; 
    }; 
    translation.BeginAnimation(TranslateTransform.YProperty, anim, HandoffBehavior.Compose); 
    button1.Content = "on"; 
    }