wpf 在代码隐藏中设置故事板.SetTargetProperty

rjee0c15  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(167)

我有一个问题,这当然是非常微不足道的,但我是一个初学者在编码C#,我只是不明白为什么代码失败。
我想动画形状,并有一个选项,在属性作为参数传递。I.o.w.:我想指定一个动画属性(路径)使用一个变量。
这让我尝试以下操作:

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()中的变量的提示?

svdrlsy4

svdrlsy41#

@克莱门斯:太好了,这些评论解决了我的问题,从我的Angular 来看是答案。
圆括号很重要。在PropertyPath XAML Syntax的动画目标的属性路径一节中有详细说明。没有圆括号的版本假设有一个Rectangle属性,该属性包含一个具有Width属性的对象,而您没有。您可以简单地编写new PropertyPath("Width")
甚至更简单:target.BeginAnimation(UIElement.WidthProperty, doubleAni)。请注意,您根本不需要故事板。
目前,我认为从克莱门斯的评论中学到了什么:
工作原理:

myPropertyPath = new PropertyPath("(Rectangle.Width)");
string _mypropertypathvariablestring = "(Rectangle.Width)"; 
string _mypropertypathvariablestring = "Width";

字符串
失败的故障:

myPropertyPath = new PropertyPath("Rectangle.Width");
string _mypropertypathvariablestring = "Rectangle.Width";


I.o.w.:无论何时,当类型要在PropertyPath中指定时,它都需要使用圆括号来表示“部分限定”,并且该类型位于默认的XML命名空间中,就像Rectangle这样的形状一样。在所有其他情况下,只需属性本身就足够了。
因为我试图实现一个纯CodeBehind解决方案,所以我没有考虑“PropertyPath XAML”,而是坚持使用“PropertyPath Class“,它更简洁,不涉及“paranthesis”语法。
但我最初的错误是误解,PropertyPath必须包括属性(链)所附加的对象,这是由工作语法选项推动的

myPropertyPath = new PropertyPath("(Rectangle.Width)");


这是我通过尝试和错误发现的,没有理解括号的含义。
也感谢您指出不使用故事板实现动画的选项,并通过BeginAnimation提出更好的实现选项。

相关问题