I have a problem which is certainly very trivial, but i am a beginner in coding C# and i simply can't understand why the code fails.
I want to animate shapes and have the option to pass in the property as a parameter. I.o.w.: i want to specify an animation property (path) using a variable.
This leads me to try the following:
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();
}
}
The compilation succeeds, but execution throws exception with the message:
System.InvalidOperationException: Cannot resolve all property references in the property path '"Rectangle.Width"'
at
sb.Begin();
I don't understand how option 1 and 2 differ (which are meant to be implemented not at the same time).
Could someone help by telling me what i misunderstand? Most likely s.th. on the conceptual level
And maybe providing a hint how to best use variables in new PropertyPath()
?