Old Account
Old Account

Reputation: 75

C# Windows 8/Modern UI - Animating Margin Property

I'm trying to create a Win8 App, and one of the problems I'm facing right now is animating the Margin property.

At first, I tried the DoubleAnimation on the Margin.Left property, but after screwing with some exceptions, and Googling a bit, I figured out that I can't animate a "non-DependencyProperty". (which actually makes sense)

So, I found out that the only way I can actually animate the margin property, is to use the ObjectAnimationUsingKeyFrames object, but this is just a frame-by-frame states for an object. It doesn't make any animation, just reposition my Ellipse on the canvas.

So my question; I somehow create a nice and clean animation on the Margin property, without adding a bunch of DiscreteObjectKeyFrame objects with different values?

Upvotes: 1

Views: 516

Answers (2)

Nigel Sampson
Nigel Sampson

Reputation: 10609

Instead of trying to animate the margin to reposition the Ellipse in the Canvas you can animate either Canvas.Left / Canvas.Top or using a RenderTransform and animating the TranslateX / TranslateY properties.

I would personally recommend the second option (using a RenderTransform) as this actually creates what's called an "Independent animation" that will run more performantly.

Upvotes: 2

ZombieSheep
ZombieSheep

Reputation: 29953

As Nigel mentioned, this is typically best achieved by animating the TranslateX or TranslateY properties of a CompsiteTransform or a TranslateTransform, as follows.

<Storyboard x:Name="ShowThatFunkyEllipse">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="MyMovingElement">
        <EasingDoubleKeyFrame KeyTime="0" Value="-350"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="0" />
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

... snip ...

<Ellipse x:Name="MyMovingElement">
    <Ellipse.RenderTransform>
        <CompositeTransform TranslateX="-350" />
    </Ellipse.RenderTransform>
</Ellipse>

Note that I used DoubleAnimationUsingKeyframes in this example - it gives more flexibility if your animation is non-linear, but you can just use a simple DoubleAnimation if you so desired. Also, the CompositeTransform can be switched out to a TranslateTransform instead if you prefer. I tend to use CompositeTransform to once again allow more to happen on the element (rotations, etc)

Upvotes: 1

Related Questions