Need help fixing WPF C# Storyboard in code behind

74 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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

You neither need a Storyboard, nor a TransformGroup. In general, you rarely need Storyboards in code, they are meant to be used in XAML.

This code is sufficient:

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