如何获取动态创建的故事板的目标属性?我的代码只返回null

时间:2011-06-04 18:00:07

标签: c# wpf silverlight

Storyboard.SetTargetProperty设置动画目标属性,但下一行的Storyboard.GetTargetProperty将返回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;

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

可以使用PropertyPathDependencyProperty初始化StringStoryboard如何处理PropertyPath取决于它的初始化方式。

SetTargetProperty传递了PropertyPath时,DependencyProperty已使用DependencyProperty初始化,然后它会检索PropertyPath并丢弃DependencyProperty,它会使用不同的SetTargetProperty用于存储此PropertyPath的内部附加属性。

仅当为TargetProperty分配了已使用字符串初始化的GetTargetProperty时,才会实际设置附加属性TargetProperty

不幸的是,SetTargetProperty只返回GetTargetProperty的值,而不管对位null的行为如何。因此SetTargetProperty会在使用PropertyPath调用DependencyProperty时返回TargetProperty,因为 Storyboard.SetTargetProperty(a, new PropertyPath("(Canvas.Top)")); 值实际上从未得到{{1}}设置在第一位。

如果您将初始化更改为: -

{{1}}

然后你的代码就可以了。