WPF故事板动画不起作用

时间:2013-02-10 06:58:34

标签: c# wpf animation 3d storyboard

我有自定义3D模型类(Model),它包含Visual3D元素和Storyboard(sb)来保存与该模型相关的动画。我正在尝试使用Storyboard旋转Visual3D元素,但遗憾的是它无效。

以下是代码段

public void AnimationRotate(Model model, double duration, double startTime, RepeatBehavior behaviour)
    {

        //Rotate transform 3D
        RotateTransform3D rotateTransform = new RotateTransform3D();

        //assign transform to the model
        model.Visual3D.Transform = Transform3DHelper.CombineTransform(model.Visual3D.Transform, rotateTransform);

        //define the rotation axis
        AxisAngleRotation3D rotateAxis = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 180);

        //create 3D rotation animation
        Rotation3DAnimation rotateAnimation = new Rotation3DAnimation(rotateAxis, TimeSpan.FromSeconds(0.5));

        //rotation behaviour
        rotateAnimation.RepeatBehavior = behaviour;

        //start animation from time
        rotateAnimation.BeginTime = TimeSpan.FromSeconds(startTime);

        //begin animation - THIS WORKS FINE
       // rotateTransform.BeginAnimation(RotateTransform3D.RotationProperty, rotateAnimation);

        Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath(RotateTransform3D.RotationProperty));
        Storyboard.SetTarget(rotateAnimation, rotateTransform);

        //add animation to the storyboard of the model
        model.sb.Children.Add(rotateAnimation);

        //BUT THIS APPROACH IS NOT WOKRING
        model.sb.Begin();

    }

1 个答案:

答案 0 :(得分:3)

问题在this answer中描述。

您需要为转换注册名称,而不是使用Storyboard.SetTarget,而是调用Storyboard.SetTargetName。此外,您必须调用Storyboard.Begin(FrameworkElement)并传递一个FrameworkElement,其中相应的名称范围为参数(this)。

RegisterName("RotateTransform", rotateTransform);
Storyboard.SetTargetName(rotateAnimation, "RotateTransform");
...
model.sb.Begin(this);

另外我想你需要在某处清除Storyboard的Children,或者在动画开始时创建一个新的Storyboard。