简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM