Cherry
Cherry

Reputation: 149

WPF using Animation to move a component

I only have experience with C/C++ and just moved to C# and WPF. I want to create an animation to move a component(e.g an image), but I don't know why the following is illegal:

ThicknessAnimation a = new ThicknessAnimation(...);

Image1.BeginAnimation(Image1.Margin, a); // illegal. Image.Margin illegal too

It seems just can't use Margin here. Of course create a timer and create Thickness objects for Margin manually can work, but that will be dull and if Animation is possible, it will be more elegant.

Is a storyboard required here? I heard some says create a storyboard and you can use Margin property, but I don't know storyboard at all and can't understand that. Thanks

Upvotes: 2

Views: 1140

Answers (1)

aybe
aybe

Reputation: 16662

You do animate dependency properties, not regular ones so try Image.MarginProperty instead.

These are static fields inside the type or base type you are targeting.

public static readonly DependencyProperty MarginProperty

In your case, it is defined in FrameworkElement.

References :

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.marginproperty.aspx

http://msdn.microsoft.com/en-us/library/ms590761.aspx

For more complex animations you would need a storyboard :

Storyboard objects enable you to combine timelines that affect a variety of objects and properties into a single timeline tree, making it easy to organize and control complex timing behaviors.

http://msdn.microsoft.com/en-us/library/ms742868.aspx

EDIT :

When looking at Intellisense you can see that the associated dependency property sits below the conventional property.

enter image description here

I previously mentionned that you had to use Image.MarginProperty but in fact you can just ignore the 'Image.' part as the object does inherit from that base type already, like animating 'this' :

enter image description here

Upvotes: 3

Related Questions