Storyboard.SetTargetProperty 设置动画目标属性,但下一行的 Storyboard.GetTargetProperty 将返回 null。
以下代码在倒数第二行崩溃, Storybard.SetTargetProperty(a, Storyboard.GetTargetProperty(a)); 在 DoubleAnimation a 被分配了一个目标属性之后。任何帮助将不胜感激!
删除该行会生成一个 Storyboard,该 Storyboard可以正确地为矩形设置动画。
完整代码在这里:
例如,
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
可以用 DependencyProperty
或 String
初始化。 Storyboard
如何处理 PropertyPath
取决于它是如何初始化的。
当 SetTargetProperty
被传递一个 PropertyPath
时,它已经用 DependencyProperty
初始化,然后它检索 DependencyProperty
和丢弃 PropertyPath
,它使用不同的内部附加属性来存储此 DependencyProperty
。
只有当 SetTargetProperty
被分配了一个已用字符串初始化的 PropertyPath
时,它才会实际设置附加属性 TargetProperty
。
不幸的是,GetTargetProperty
只是返回 TargetProperty
的值,而不管对应部分 SetTargetProperty
的行为如何。因此,当使用 PropertyPath
调用 SetTargetProperty
并使用 DependencyProperty 初始化时,
因为 GetTargetProperty
将返回 null
TargetProperty
值实际上从未真正设置过。
如果您将初始化更改为:-
Storyboard.SetTargetProperty(a, new PropertyPath("(Canvas.Top)"));
然后你的代码就可以工作了。
关于c# - 如何获取动态创建的 Storyboard的目标属性?我的代码只返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238472/