[英]Set Storyboard.SetTargetProperty in code-behind
我有一个肯定很琐碎的问题,但是我是C#编码的初学者,我根本不明白为什么代码会失败。
我想设置形状的动画,并可以选择将属性作为参数传递。 爱荷华州:我想使用变量指定动画属性(路径)。
这使我尝试以下操作:
public static class HelperExtension
{
public static void Animate(this UIElement target, string propertyToAnimate, double? from, double to, int duration = 3000, int startTime = 0)
{
var doubleAni = new DoubleAnimation
{
To = to,
From = from,
Duration = TimeSpan.FromMilliseconds(duration)
};
Storyboard.SetTarget(doubleAni, target);
PropertyPath myPropertyPath;
// option 1: fails:
string _mypropertypathvariablestring = "Rectangle.Width";
myPropertyPath = new PropertyPath(_mypropertypathvariablestring);
// option 2: succeeds:
myPropertyPath = new PropertyPath("(Rectangle.Width)");
Storyboard.SetTargetProperty(doubleAni, myPropertyPath);
var sb = new Storyboard
{
BeginTime = TimeSpan.FromMilliseconds(startTime)
};
sb.Children.Add(doubleAni);
sb.Begin();
}
}
编译成功,但是执行会引发异常消息:
System.InvalidOperationException:无法解析属性路径“ Rectangle.Width”中的所有属性引用
在
sb.Begin();
我不明白选项1和2有何不同(这意味着不能同时实现)。
有人可以告诉我我误会了什么吗? 最有可能的 在概念上
并可能提示如何在new PropertyPath()
最好地使用变量?
// @ Clemens:完美,解决了我的问题,从我的角度来看就是答案。
我正在寻找将评论标记为答案的选项,但是显然有理由( 将评论标记为问题的答案 )没有它。 如果主持人可以选择将Clemens评论标记为答案并表示同意,我会认为这是正确的选择。
暂时总结一下我认为从克莱门斯的评论中学到的东西:
有效的语法:
myPropertyPath = new PropertyPath("(Rectangle.Width)");
string _mypropertypathvariablestring = "(Rectangle.Width)";
string _mypropertypathvariablestring = "Width";
失败的语法:
myPropertyPath = new PropertyPath("Rectangle.Width");
string _mypropertypathvariablestring = "Rectangle.Width";
Iow:每当要在PropertyPath中指定类型时,都需要使用括号来表示“部分限定”,并且该类型必须位于默认的XML名称空间中,就像Rectangle一样。 在所有其他情况下,仅财产本身就足够了。
由于我尝试实现纯CodeBehind解决方案,因此我没有考虑“ PropertyPath XAML语法 ”,而是坚持使用“ PropertyPath Class ”,它更加简洁并且不涉及“ paranthesis”语法。
但是我最初的错误是一个误解,即PropertyPath必须包含属性(链)附加到的对象,这是由工作语法选项引起的
myPropertyPath = new PropertyPath("(Rectangle.Width)");
我是通过反复试验发现的,却没有理解括号的含义。
也感谢您指出无需使用情节提要而实现动画的选项,并通过BeginAnimation提出了更好的实现选项。
再次感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.