WPF Xaml旋转动画保持最终状态

时间:2015-04-15 14:50:54

标签: c# wpf xaml animation

我在窗口中有一个矩形和一个按钮,每次我点击按钮我想用动画旋转60度的矩形,我的问题是每次我点击按钮它都会恢复到一个角度0.如何保持动画的结束状态,以便在第一次点击时从0到60度,在第二次点击时从60到120,等等......?

这是我到目前为止所拥有的...... 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>

代码背后......

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

1 个答案:

答案 0 :(得分:1)

您应该重用XAML中定义的RotateTransform,例如

<Rectangle RenderTransformOrigin="0.5,0.5" ...>
    <Rectangle.RenderTransform>
        <RotateTransform x:Name="transform"/>
    </Rectangle.RenderTransform>
</Rectangle>

并通过设置其By属性来运行动画:

transform.BeginAnimation(RotateTransform.AngleProperty,
    new DoubleAnimation
    {
        By = 60d,
        Duration = TimeSpan.FromSeconds(0.3)
    });