如何通过C#而不是XAML更改对象的Y投影轴和颜色

时间:2011-08-18 04:46:44

标签: c# wpf silverlight xaml storyboard

我正在开发一个Silverlight项目,我将通过在Y投影轴上旋转矩形来“翻转”矩形。我还将在动画中间更改颜色,使其看起来像矩形的背面是不同的颜色。我可以在XAML中做到这一点没有问题,但我需要通过代码执行此操作,因为我想动态翻转不同的矩形。我不想为网格上的每个矩形创建动画。这是我的XAML的样子:

<Storyboard x:Name="Flip1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="rectangle">
                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle">
                <EasingColorKeyFrame KeyTime="0:0:0.5" Value="Blue"/>
                <EasingColorKeyFrame KeyTime="0:0:0.6" Value="Red"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>

我已经多次从代码中创建了故事板,但是这个让我对EasingDoubleKeyFrames感到有点难过。任何想法如何去做?

1 个答案:

答案 0 :(得分:1)

这应该是第一个动画的翻译:

var anim = new DoubleAnimationUsingKeyFrames();
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0), Value = 0 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.5), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.6), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 0 });
Storyboard.SetTarget(anim, rectangle);
Storyboard.SetTargetProperty(anim, new PropertyPath("Projection.RotationY"));

使用Storyboards时,您还需要在名称范围内注册目标,我建议您阅读Storyboard类的完整参考。