Search code examples
c#wpfanimationstoryboardtransform

How to Animate Transforms in code behind?


I have a Button. For some reason, I would like to apply transforms in code behind. And The transforms work fine. But when I try to add animations on the transforms, the animations don't take effect. My code is as below.

<Grid x:Name="grid">
    <Button Height="40" Width="120" Content="Button"
            x:Name="button" Click="button_Click"> 
    </Button>
</Grid>

and in codebehind when button Clicked is :

private void button_Click(object sender, RoutedEventArgs e)
{
    var animation = new DoubleAnimation(0, 20, new Duration(TimeSpan.FromSeconds(1)));
    var story = new Storyboard();
    story.Children.Add(animation);
    Storyboard.SetTarget(animation, button);
    Storyboard.SetTargetProperty(animation, new PropertyPath(TranslateTransform.YProperty));
    story.Begin();
}

Solution

  • In order to animate a TranslateTransform, there has to be one assigned to the Button's RenderTransform or LayoutTransform property, either in XAML

    <Button x:Name="button" Click="button_Click" ...>
        <Button.RenderTransform>
            <TranslateTransform/>
        </Button.RenderTransform>
    </Button>
    

    or in code behind

    button.RenderTransform = new TranslateTransform();
    

    Then you do not need a Storyboard, because you can directly animate the transform like

    var animation = new DoubleAnimation(0, 20, TimeSpan.FromSeconds(1));
    
    button.RenderTransform.BeginAnimation(TranslateTransform.XProperty, animation);
    

    With a Storyboard, you would have to set the correct property path:

    var animation = new DoubleAnimation(0, 20, TimeSpan.FromSeconds(1));
    Storyboard.SetTarget(animation, button);
    Storyboard.SetTargetProperty(animation, new PropertyPath("RenderTransform.X"));
    
    var story = new Storyboard();
    story.Children.Add(animation);
    story.Begin();