How to rotate a grid using storyboard in c # wpf code

I want to rotate a simple grid with a storyboard in c # code in wpf my xaml code

<Window x:Class="rotate_test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:rotate_test"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid Name="my_grid">
            <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="150,170,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
        </Grid>
    </Grid>
</Window>

which have a grid and one button in it in the onclick event for the button i use

    Storyboard storyboard = new Storyboard();
    DoubleAnimation rotateAnimation = new DoubleAnimation()
    {
        From = 0,
        To = 360,
        Duration = new Duration(TimeSpan.FromSeconds(10.0))
};
    Storyboard.SetTarget(rotateAnimation, my_grid);
    Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath("(UIElement.RenderTransform).(RotateTransform.Angle)"));

    storyboard.Children.Add(rotateAnimation);
    storyboard.Begin();

but the dose does not work, what is my problem? How can I set acceleration for animation? Thnx

+1
source share
1 answer

You must initialize the grid RenderTransformbefore you can animate it.

<Grid Name="my_grid">
    <Grid.RenderTransform>
        <RotateTransform />
    </Grid.RenderTransform>
</Grid>

You can also animate directly RotateTransformwithout a storyboard.

Just enter a name

<RotateTransform x:Name="transform" />

and animate it in code similar to

transform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);

In addition, DoubleAnimation has several properties that control acceleration and deceleration, for example AccelerationRatio, DecelerationRatioand EasingFunction.

+2

All Articles