如何使用纯C#中的ObjectAnimationUsingKeyFrame?

时间:2013-01-23 06:06:31

标签: c# wpf xaml

我想动态地从C#做这样的事情:

<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>

但我无法弄清楚这个XAML的C#等价物。具体来说,我希望从C#中更改Image对象中显示的图像。

我试过了:

        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();

我收到错误“附加信息:没有适用的名称范围来解析名称'image'。”

在我控制的XAML中,x:name是“image”

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

我也试过

Storyboard.SetTargetName(animation,image.Name);

并得到了同样的错误。

1 个答案:

答案 0 :(得分:0)

确定!我想出了C#等价物。

        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();

我使用“SetTarget”代替“SetTargetName”