代码之家  ›  专栏  ›  技术社区  ›  ZioGio

需要帮助修复代码隐藏中的WPF C#情节提要

  •  0
  • ZioGio  · 技术社区  · 2 年前

    使用下面的代码示例,myImage只沿Y轴移动,而不沿X轴移动。我需要myImage同时沿X轴和Y轴移动。Image myImage存在于画布中的XAML中。建议?

    感谢您的时间和帮助!

    DoubleAnimationUsingKeyFrames AnimateX = new DoubleAnimationUsingKeyFrames();
    AnimateX.KeyFrames.Add(new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));
    AnimateX.KeyFrames.Add(new EasingDoubleKeyFrame(80, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))));
    
    DoubleAnimationUsingKeyFrames AnimateY = new DoubleAnimationUsingKeyFrames();
    AnimateY.KeyFrames.Add(new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));
    AnimateY.KeyFrames.Add(new EasingDoubleKeyFrame(34, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))));
    
    TransformGroup tg = new TransformGroup();
    TranslateTransform translation = new TranslateTransform();
    string translationName = "myTranslation";
    RegisterName(translationName, translation);
    tg.Children.Add(translation);
    myImage.RenderTransform = tg;
    
    Storyboard s = new Storyboard();
    Storyboard.SetTargetName(s, translationName);
    Storyboard.SetTargetProperty(s, new PropertyPath(TranslateTransform.XProperty));
    Storyboard.SetTargetProperty(s, new PropertyPath(TranslateTransform.YProperty));
    string storyboardName = "s";
    Resources.Add(storyboardName, s);
    s.Children.Add(AnimateX);
    s.Children.Add(AnimateY);
    s.Begin();
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   MIHOW    2 年前

    问题在于代码的最后一段,请将其更改为

    Storyboard s = new Storyboard();
    Storyboard.SetTargetName(s, translationName);
    Storyboard.SetTargetProperty(AnimateX, new PropertyPath(TranslateTransform.XProperty));
    Storyboard.SetTargetProperty(AnimateY, new PropertyPath(TranslateTransform.YProperty));
    string storyboardName = "s";
    Resources.Add(storyboardName, s);
    s.Children.Add(AnimateX);
    s.Children.Add(AnimateY);
    s.Begin(myImage);
    
        2
  •  0
  •   Clemens    2 年前

    您既不需要情节提要,也不需要TransformGroup。一般来说,代码中很少需要情节提要,它们是用来在XAML中使用的。

    此代码足够:

    var animateX = new DoubleAnimationUsingKeyFrames();
    animateX.KeyFrames.Add(
        new EasingDoubleKeyFrame(80, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))));
    
    var animateY = new DoubleAnimationUsingKeyFrames();
    animateY.KeyFrames.Add(
        new EasingDoubleKeyFrame(34, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))));
    
    var translation = new TranslateTransform();
    myImage.RenderTransform = translation;
    
    translation.BeginAnimation(TranslateTransform.XProperty, animateX);
    translation.BeginAnimation(TranslateTransform.YProperty, animateY);