简体   繁体   中英

How can you use ObjectAnimationUsingKeyFrames from pure C#?

I want to dynamically, from C#, do something like this:

<ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
                               Storyboard.TargetName="image"
                               Storyboard.TargetProperty="(Image.Source)">
  <DiscreteObjectKeyFrame KeyTime="00:00:00.7000000">
    <DiscreteObjectKeyFrame.Value>
      <BitmapImage UriSource="check_24.png" />
    </DiscreteObjectKeyFrame.Value>
  </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>

but I can't figure out the C# equivalent to this XAML. Specifically, I want to, from C#, change the image that's displayed in an Image object.

I tried this:

        ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();
        animation.BeginTime = TimeSpan.FromSeconds(0);
        Storyboard.SetTargetName(animation, "image");
        Storyboard.SetTargetProperty(animation, new PropertyPath("(Image.Source)"));
        DiscreteObjectKeyFrame keyFrame = new DiscreteObjectKeyFrame(BitmapFrame.Create(uri), TimeSpan.FromSeconds(0.7));
        animation.KeyFrames.Add(keyFrame);
        myStoryboard.Children.Add(animation);
        myStoryboard.Begin();

and I get the error "Additional information: No applicable name scope exists to resolve the name 'image'."

In my XAML for the controls, the x:name is "image"

<Image x:Name="image" ... />

I also tried

Storyboard.SetTargetName(animation, image.Name);

and got the same error.

Ok! I figured out the C# equivalent.

        ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();
        animation.BeginTime = TimeSpan.FromSeconds(0);
        Storyboard.SetTarget(animation, image);
        Storyboard.SetTargetProperty(animation, new PropertyPath("(Image.Source)"));
        DiscreteObjectKeyFrame keyFrame = new DiscreteObjectKeyFrame(BitmapFrame.Create(uri), TimeSpan.FromSeconds(0.7));
        animation.KeyFrames.Add(keyFrame);
        myStoryboard.Children.Add(animation);
        myStoryboard.Begin();

I used "SetTarget" instead of "SetTargetName"

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