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;
任何帮助都会非常感激。
答案 0 :(得分:2)
可以使用PropertyPath
或DependencyProperty
初始化String
。 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)"));
值实际上从未得到{{1}}设置在第一位。
如果您将初始化更改为: -
{{1}}
然后你的代码就可以了。