Search code examples
c#wpfanimationblend

Shifting a Button Animation using System.Windows.Media.Animation


I have a Button in my Window, how do I use code behind in C# to go about animating it to shift to the left by lets say 100 pixels once I click on it.

private void myButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    // TODO: Add event handler implementation here.
    DoubleAnimation _DoubleAnimation = new DoubleAnimation();
    _DoubleAnimation.From = 0;
    _DoubleAnimation.To = 100;
    _DoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));

    myButton.BeginAnimation(Button.RenderTransformOriginProperty, _DoubleAnimation);
}

Solution

  • If you want to change the size, in this case must be WidthProperty in Animation:

    myButton.BeginAnimation(Button.WidthProperty, _DoubleAnimation);
    

    To avoid sharp transition in the Animation, you must explicitly set the Width of the Button:

    <Button Name="myButton" 
            Width="30" 
            Content="Test"  
            Click="myButton_Click" />
    

    And in Animation specify only To value:

    private void myButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        DoubleAnimation _DoubleAnimation = new DoubleAnimation();
        _DoubleAnimation.To = 100;
        _DoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));
    
        myButton.BeginAnimation(Button.WidthProperty, _DoubleAnimation);
    }
    

    If you want to shift Button in Animation, you can use ThicknessAnimation:

    Thanks for the remark to @Rohit Vats

    private void myButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        ThicknessAnimation animation = new ThicknessAnimation(new Thickness(0), 
                                                              new Thickness(100, 0, 0, 0), 
                                                              new Duration(new TimeSpan(0, 0, 1)),
                                                              FillBehavior.HoldEnd);
    
        myButton.BeginAnimation(Button.MarginProperty, animation);
     }