Wxy
Wxy

Reputation: 11

How to rotate animation my button when click in c# wpf

these are my declaration for my DoubleAnimation and storyboard

private Storyboard openmenurotateSB;

DoubleAnimation openMenuRotate = new DoubleAnimation();
openMenuRotate.From = 0;
openMenuRotate.To = 90;
openMenuRotate.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
openMenuRotate.FillBehavior = FillBehavior.Stop;
openMenuRotate.AutoReverse = true;
openmenurotateSB = new Storyboard();
openmenurotateSB.Children.Add(openMenuRotate);
Storyboard.SetTargetName(openMenuRotate, OpenMenuButton.Name);
Storyboard.SetTargetProperty(openMenuRotate, new PropertyPath(RotateTransform.AngleProperty));

when click, begin rotate animation

private void OpenMenu_Click(object sender, RoutedEventArgs e)
        {
            openmenurotateSB.Begin(OpenMenuButton);
        }

There is no any error or exception, it just does not work.

Thanks in advance.

Xing Yik

Upvotes: 1

Views: 258

Answers (1)

Clemens
Clemens

Reputation: 128181

A RotateTransform should be assigned to either the RenderTransform or the LayoutTransform property of the Button.

<Button Content="Open Menu" Click="OpenMenu_Click"
        RenderTransformOrigin="0.5,0.5">
    <Button.RenderTransform>
        <RotateTransform x:Name="rotateTransform"/>
    </Button.RenderTransform>
</Button>

You do not need to use a Storyboard. Just directly animate the RotateTransform.

private void OpenMenu_Click(object sender, RoutedEventArgs e)
{
    var animation = new DoubleAnimation
    {
        To = 90,
        Duration = TimeSpan.FromSeconds(1),
        FillBehavior = FillBehavior.Stop,
        AutoReverse = true
    };

    rotateTransform.BeginAnimation(
        RotateTransform.AngleProperty, animation);
}

or if you don't want to assign an x:Name to the RotateTransform or have assigned the RenderTransform property in code behind:

((UIElement)sender).RenderTransform.BeginAnimation(
    RotateTransform.AngleProperty, animation);

Upvotes: 2

Related Questions