2011-06-04 25 views
2

Storyboard.SetTargetProperty設置一個動畫目標屬性,但下面一行中的Storyboard.GetTargetProperty將返回null。如何獲得動態創建的故事板的目標屬性?我的代碼只返回null

以下代碼在倒數第二行崩潰, Storybard.SetTargetProperty(a,Storyboard.GetTargetProperty(a));在DoubleAnimation a之後已經分配了一個目標屬性的 。任何幫助將不勝感激!

刪除該行會生成一個可正確動畫矩形的故事板。

完整的代碼是在這裏:

例如,

public Storyboard moveDown(Rectangle rect){ 
//Set up the animation 

DoubleAnimation a=new DoubleAnimation(); 
a.RepeatBehavior=new RepeatBehavior(1); 
a.FillBehavior=FillBehavior.HoldEnd; 
a.From=0; 
a.To=100; 
a.Duration=10; 

//Set up the Storyboard 
Storyboard sb=new Storyboard(); 
sb.Children.Add(a); 
sb.Duration=a.Duration; 

//Assign animation's target and property. This resulting animation works great. 
Storyboard.SetTarget(a, rect); 
Storyboard.SetTargetProperty(a, new PropertyPath(Canvas.TopProperty)); 

//Here's the problem: I can't get the propertypath back with GetTargetProperty 
//targetProperty is null. 
var targetProperty=Storyboard.GetTargetProperty(a); 

//And this line crashes the program. It's only here for debugging purposes. 
Storyboard.SetTargetProperty(a, Storyboard.GetTargetProperty(a)); 

//You need to say canvas.Resources.Add("a unique id in quotes", sb) if you want it to 
//run on a canvas. 

return sb; 

任何幫助將非常感激。

+0

只是在黑暗中隨機拍攝,但這樣做的工作? 'Storyboard.SetTargetProperty(a,new PropertyPath(「(Canvas.TopProperty)」));' – keyboardP 2011-06-04 18:53:26

回答

2

A PropertyPath可以初始化爲DependencyPropertyStringStoryboard如何處理PropertyPath取決於它如何被初始化。

SetTargetProperty傳遞已初始化用DependencyProperty一個PropertyPath然後它檢索DependencyProperty並丟棄PropertyPath,它採用了不同的內部附加屬性存儲此DependencyProperty

只有當SetTargetProperty被分配了PropertyPath已被初始化爲字符串時,它是否實際設置了附加屬性TargetProperty

不幸的是,GetTargetProperty僅僅返回TargetProperty的值,無論計數器部分SetTargetProperty的行爲如何。因此GetTargetProperty將返回null已調用SetTargetPropertyPropertyPath已被初始化爲DependencyProperty,因爲TargetProperty值從未真正被設置在首位。

如果你改變你的初始化這個: -

Storyboard.SetTargetProperty(a, new PropertyPath("(Canvas.Top)")); 

那麼你的代碼將工作。

+0

非常感謝!這是不可思議的幫助。 – Khelvaster 2011-06-06 22:43:29

相關問題