简体   繁体   中英

WPF DoubleAnimation from CodeBehind

In the MainWindow.xaml I have this:

<view:CircularProgressBar Percentage="25"
                          ...
                          x:Name="speedoBar"/>

I had Percentage bound to a value I get from further outside. The problem is: it sets the value directly but I need to have a DoubleAnimation from where I am now to the value I just got.

In the part where I get the value I tried to create a new Storyboard and DoubleAnimation but nothing I try works. I could think of creating a new DependencyProperty variable that will be DoubleAnimated and bind Percentage to it. But this value would be a double and I wasn't able to start a DoubleAnimation to a usual double-value. All I can find on the internet is a DoubleAnimation to an object's DpendencyProperty.

Then I tried to do the animation on the percentage value but the codebehind doesn't recognize it and VisualStudio suggests to create a new DependencyProperty-variable.

What I have so far is this:

// get the old value
speedCopy = speedoBar.Percentage;

DoubleAnimation speedDoubleAni =
new DoubleAnimation(speedCopy, (double)(vehicleDataViewModel.Speed), new Duration(new TimeSpan(0, 0, 10)));

Storyboard.SetTargetName(speedDoubleAni, "speedoBar.Percentage");
Storyboard.SetTargetProperty(speedDoubleAni, new PropertyPath(DoubleAnimation.ByProperty));

Storyboard story = new Storyboard();
story.Children.Add(speedDoubleAni);
story.Begin();

But it isn't working and shows the error at story.Begin(); which means it's harder to find out the real problem D:

So how would you do that at all and what am I doing wrong here?

You set TargetName and TargetProperty to wrong values. From MSDN :

  • TargetName : Gets or sets the name of the object to animate. The object must be a FrameworkElement, FrameworkContentElement, or Freezable.
  • TargetProperty : Gets or sets the property that should be animated.

So in your case TargetName would be speedoBar and TargetProperty would be Percentage but you can set Target directly to speedoBar and, assuming that CircularProgressBar.Percentage is a DependencyProperty , below code should work:

Storyboard.SetTarget(speedDoubleAni, speedoBar);
Storyboard.SetTargetProperty(speedDoubleAni, new PropertyPath("Percentage"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM