How to animate Margin property in WPF
You can't animate Margin.Left (because Left
is not a dependency property), but you can animate Margin
. Use ObjectAnimationUsingKeyFrames
:
<Storyboard x:Key="MoveMe">
<ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="GroupTileSecond"
Storyboard.TargetProperty="Margin">
<DiscreteObjectKeyFrame KeyTime="00:00:00">
<DiscreteObjectKeyFrame.Value>
<Thickness>134,70,0,0</Thickness>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="00:00:03">
<DiscreteObjectKeyFrame.Value>
<Thickness>50,70,0,0</Thickness>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
There are some alternatives that allow you to use a DoubleAnimation
, rather than key frames:
- Place your target inside a Canvas, and animate its x position using
Canvas.Left
. - Apply a
TranslateTransform
to your target, and animate its x position usingTranslateTransform.X
.
Margin
property can be animated using ThicknessAnimation
<Storyboard >
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" BeginTime="00:00:00">
<SplineThicknessKeyFrame KeyTime="00:00:00" Value="134, 70,0,0" />
<SplineThicknessKeyFrame KeyTime="00:00:03" Value="50, 70,0,0" />
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
Actually, ya you can do what you want to do, exactly as you want to do using RenderTransform
mixed with some DoubleAnimation
and even add some extra flair to it, for example;
<Grid x:Name="TheObject" Opacity="0">
<Grid.RenderTransform>
<TranslateTransform x:Name="MoveMeBaby" X="50" />
</Grid.RenderTransform>
<Grid.Triggers>
<EventTrigger RoutedEvent="Grid.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="MoveMeBaby"
Storyboard.TargetProperty="X">
<SplineDoubleKeyFrame KeyTime="0:0:1.25" Value="0" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="TheObject"
Storyboard.TargetProperty="Opacity">
<SplineDoubleKeyFrame KeyTime="0:0:1.55" Value="1" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
</Grid>
Will move that object 50px on the X axis and even fade it in while it does so. Give it a shot and play with the values of the X
property and the KeyTime
to get what you want. Hope this helps, cheers.