将事件侦听器附加到UWP中的MotionAnimation

时间:2018-12-29 01:42:10

标签: c# animation uwp

我以这种方式设置了MotionAnimation:

public static void StartSpringAnim(this Panel view)
{
    Visual viewVisual = ElementCompositionPreview.GetElementVisual(view);
    SpringScalarNaturalMotionAnimation springAnimation = viewVisual.Compositor.CreateSpringScalarAnimation();
    springAnimation.Period = TimeSpan.FromSeconds(0.1);
    springAnimation.DampingRatio = 0.5f;
    springAnimation.StopBehavior = AnimationStopBehavior.SetToFinalValue;
    springAnimation.InitialValue = (float) view.Margin.Left;
    springAnimation.FinalValue = (float)view.Margin.Left + 50;
    viewVisual.StartAnimation("Offset.X", springAnimation);
}

我想在动画上附加一个事件处理程序,以便动画完成后得到通知(以便我可以执行一些进一步的操作)。

如何获得这样的结果?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用CompositionScopedBatch

跟踪合成动画
    public static void StartSpringAnim(this Panel view)
    {
        Visual viewVisual = ElementCompositionPreview.GetElementVisual(view);
        SpringScalarNaturalMotionAnimation springAnimation = viewVisual.Compositor.CreateSpringScalarAnimation();
        springAnimation.Period = TimeSpan.FromSeconds(0.1);
        springAnimation.DampingRatio = 0.5f;
        springAnimation.StopBehavior = AnimationStopBehavior.SetToFinalValue;
        springAnimation.InitialValue = (float)view.Margin.Left;
        springAnimation.FinalValue = (float)view.Margin.Left + 50;

        var scopedBatch = viewVisual.Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
        scopedBatch.Completed += Animation_Completed;
        viewVisual.StartAnimation("Offset.X", springAnimation);
        scopedBatch.End();
    }

    private void Animation_Completed(object sender, CompositionBatchCompletedEventArgs args)
    {
        //this will fire on animation complete
    }

此处有更多信息:https://docs.microsoft.com/en-us/uwp/api/windows.ui.composition.compositionscopedbatch