Reputation: 3
I have a rectangle and a button in a window and each time I click the button I would like to rotate the rectangle 60 degrees with an animation, my problem is that each time I click the button it reverts back to an angle of 0. How do I maintain the end state of the animation so as to go from 0 to 60 degrees on the first click, 60 to 120 on the second, etc...?
Here is what I have so far... Xaml:
<Grid>
<StackPanel>
<Border BorderBrush="White" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle Width="100" Height="100" x:Name="rect" RenderTransformOrigin=".5,.5" Fill="Red"/>
</Border>
<Button Width="100" Height="100" Click="Button_Click">Rotate</Button>
</StackPanel>
</Grid>
And code behind...
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation d2 = new DoubleAnimation(60, new Duration(TimeSpan.FromSeconds(0.3)), FillBehavior.HoldEnd);
RotateTransform rt = new RotateTransform();
rect.RenderTransform = rt;
d2.Completed += (s, eArgs) => rect.RenderTransform = new RotateTransform(60);
rt.BeginAnimation(RotateTransform.AngleProperty, d2);
}
Upvotes: 0
Views: 553
Reputation: 128116
You should reuse a RotateTransform that is defined in XAML, like
<Rectangle RenderTransformOrigin="0.5,0.5" ...>
<Rectangle.RenderTransform>
<RotateTransform x:Name="transform"/>
</Rectangle.RenderTransform>
</Rectangle>
and run the animation by setting its By
property:
transform.BeginAnimation(RotateTransform.AngleProperty,
new DoubleAnimation
{
By = 60d,
Duration = TimeSpan.FromSeconds(0.3)
});
Upvotes: 2