Search code examples
c#wpfstoryboardcode-behindtransformgroup

Need help fixing WPF C# Storyboard in code behind


Using the code sample below, myImage only moves along the Y axis, but not the X. I need myImage to move along both the X and Y axes simultaneously. Image myImage exists in the XAML within a Canvas. Suggestions?

Thank you for your time and assistance!

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

Solution

  • The problem lies in the last snippet of your code, change it to

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