c# - 如何获取动态创建的 Storyboard的目标属性?我的代码只返回 null

标签 c# wpf silverlight

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 可以用 DependencyPropertyString 初始化。 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/

相关文章:

wpf - 如何在自动列宽度内将TextBlock换行?

silverlight - 用于创建交互式图表的工具

c# - 删除隔离存储文件

c# - 如何在 WPF 的第二个屏幕中启动第二个应用程序?

c# - WPF 绑定(bind) UI(源)与属性(目标)

c# - 仅在选择 ListViewItem 时显示内容

c# - 如何使用 SDK 连接到 CRM(基于声明的身份验证和自定义 STS)

c# - 有没有办法在 C# 中注释允许的值

c# - C# MYSQL MySqlBulkLoader 可以动态转换数据类型吗?

c# - 使用 LINQ to SQL 获取 ID