Storyboard.SetTargetProperty设置动画目标属性,但是下一行中的Storyboard.GetTargetProperty将返回null。

以下代码在倒数第二行崩溃,
    Storybard.SetTargetProperty(a,Storyboard.GetTargetProperty(a));
在DoubleAnimation分配了目标属性之后。任何帮助将不胜感激!

删除该线会生成一个情节提要,可以使矩形正确地动画。

完整的代码在这里:

例如,

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;


任何帮助将非常感激。

最佳答案

PropertyPath可以用DependencyPropertyString初始化。 Storyboard如何处理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)"));


然后您的代码将起作用。

09-13 07:59