C# – Animating the height and width of an object in C#

animationc++wpf

I am trying to get these ellipses to grow but I cannot figure out how to start the animation. This is my first attempt at WPF animation and I don't quite understand how it all works.

private void drawEllipseAnimation(double x, double y)
{
    StackPanel myPanel = new StackPanel();
    myPanel.Margin = new Thickness(10);

    Ellipse e = new Ellipse();
    e.Fill = Brushes.Yellow;
    e.Stroke = Brushes.Black;
    e.Height = 0;
    e.Width = 0;
    e.Opacity = .8;
    canvas2.Children.Add(e);
    Canvas.SetLeft(e, x);
    Canvas.SetTop(e, y);

    DoubleAnimation myDoubleAnimation = new DoubleAnimation();
    myDoubleAnimation.From = 0;
    myDoubleAnimation.To = 10;
    myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
    myStoryboard = new Storyboard();
    myStoryboard.Children.Add(myDoubleAnimation);
    Storyboard.SetTargetName(myDoubleAnimation, e.Name);
    Storyboard.SetTargetProperty(myDoubleAnimation, new     PropertyPath(Ellipse.HeightProperty));
    Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Ellipse.WidthProperty));
}

Best Solution

You don't need a Storyboard here. Just do

e.BeginAnimation(Ellipse.WidthProperty, myDoubleAnimation);
e.BeginAnimation(Ellipse.HeightProperty, myDoubleAnimation);

If you really need to do it with a Storyboard, you will have to add separate animations, one per animated property, to the Storyboard. And you have to call SetTarget instead of SetTargetName when you don't apply a name. Finally you'll need to start the Storyboard by calling Begin:

DoubleAnimation widthAnimation = new DoubleAnimation
{
    From = 0,
    To = 10,
    Duration = TimeSpan.FromSeconds(5)
};

DoubleAnimation heightAnimation = new DoubleAnimation
{
    From = 0,
    To = 10,
    Duration = TimeSpan.FromSeconds(5)
};

Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(Ellipse.WidthProperty));
Storyboard.SetTarget(widthAnimation, e);

Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(Ellipse.HeightProperty));
Storyboard.SetTarget(heightAnimation, e);

Storyboard s = new Storyboard();
s.Children.Add(widthAnimation);
s.Children.Add(heightAnimation);
s.Begin();