2014-11-05 24 views
1

我想弄清楚如何在程序上生成動畫。我創建一條線,創建四個動畫,並將線的端點與動畫相關聯。我將動畫添加到故事板,然後運行故事板。WPF元素在視覺樹中,但不是動畫?

面板本身是可見的(我可以更改背景橙色,並顯示更改),但不是它的孩子。赫克我做錯了嗎?

後面的代碼:

using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Shapes; 
using System.Windows.Media.Animation; 

namespace MyProject.Animations 
{ 
    public class MyAnimation : Panel 
    { 
     private DoubleAnimation[] lineAnimation; 
     private Line line; 
     private Storyboard storyboard; 

     public MyAnimation() 
     { 
      storyboard = new Storyboard(); 

      line = new Line(); 
      line.StrokeThickness = 4; 
      line.Stroke = Brushes.Black; 
      this.Children.Add(line);  

      lineAnimation = new DoubleAnimation[4]; 
      for (int i = 0; i < 4; i++) 
      { 
       lineAnimation[i] = new DoubleAnimation(); 
       lineAnimation[i].Duration = new Duration(TimeSpan.FromSeconds(5)); 
       lineAnimation[i].AutoReverse = true; 
       lineAnimation[i].RepeatBehavior = RepeatBehavior.Forever; 

       lineAnimation[i].From = 10 * i; 
       lineAnimation[i].To = 100 * i; 

       storyboard.Children.Add(lineAnimation[i]); 
      } 

      Storyboard.SetTarget(lineAnimation[0], line); 
      Storyboard.SetTargetProperty(lineAnimation[0], new PropertyPath("X1")); 

      Storyboard.SetTarget(lineAnimation[1], line); 
      Storyboard.SetTargetProperty(lineAnimation[1], new PropertyPath("Y1")); 

      Storyboard.SetTarget(lineAnimation[2], line); 
      Storyboard.SetTargetProperty(lineAnimation[2], new PropertyPath("X2")); 

      Storyboard.SetTarget(lineAnimation[3], line); 
      Storyboard.SetTargetProperty(lineAnimation[3], new PropertyPath("Y2")); 

      storyboard.Begin(); 
     } 
    } 
} 

XAML:

<Window x:Class="MyProject.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:sdk="http://schemas.microsoft.com/netfx/2009/xaml/presentation/sdk" 
     xmlns:local="clr-namespace:MyProject" 
     xmlns:a="clr-namespace:Myproject.Animations" 
     Title="MyProject"> 

    <Grid> 
     <a:MyAnimation> 
    </Grid> 

</Window> 

檢查與史努比的應用程序,我看到我的可視化樹線。但他們並沒有被吸引。 (請注意,這是在實際應用中的調試窗口,而不是代表代碼示例,我轉錄。)

回答

3

當您從Panel派生,孩子們沒有佈局。您還必須重寫MeasureOverrideArrangeOverride方法。詳情請參閱How to: Create a Custom Panel Element

或者乾脆從帆布代替派生:

public class MyAnimation : Canvas 
{ 
    ... 
} 
+0

經過的週轉時間:2分鐘。再次感謝Clemens。 – Zaaier 2014-11-05 08:01:51