C# 自定义页面控件中的合成动画?

C# 自定义页面控件中的合成动画?,c#,xaml,animation,uwp,C#,Xaml,Animation,Uwp,我创建了一个从页面继承的自定义控件,用于设置NavigatingFrom事件的动画。然而,我似乎无法播放实际的动画。这是我的完整AltPage.cs代码: public class AltPage : Page { protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { //Set up the composition animation var _compos

我创建了一个从页面继承的自定义控件,用于设置NavigatingFrom事件的动画。然而,我似乎无法播放实际的动画。这是我的完整AltPage.cs代码:

public class AltPage : Page
{
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        //Set up the composition animation
        var _compositor = new Compositor();
        var _targetVisual = ElementCompositionPreview.GetElementVisual(this);
        var animation = _compositor.CreateScalarKeyFrameAnimation();
        animation.Duration = new TimeSpan(0, 0, 0, 0, 300);
        animation.InsertKeyFrame(1.0f, 0f);


        _targetVisual.StartAnimation("Opacity", animation);

        //Give some time for the animation to start
        Task.Delay(18);

        //Get the page to initialize while the animation is playing
        base.OnNavigatingFrom(e);
    }
}
当我运行代码时,行
\u targetVisual.StartAnimation(“不透明”,动画)
会引发System.UnauthorizedAccessException。我被告知“不允许调用方在此对象上执行此操作”。我做错了什么

当我运行代码时,行_targetVisual.StartAnimation(“不透明”,动画)会引发System.UnauthorizedAccessException。我被告知“不允许调用方在此对象上执行此操作”

合成器
对象需要从当前页面的任何
可视化
中获取。您可以使用以下代码获得合成器:

ElementCompositionPreview _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
在导航之前引发,但我们不能延迟以阻止页面导航。当我们使用
Task.Delay
时,我们需要一个
wait
来让它同步工作。但它会使整个函数异步运行(
async
将在使用
wait
时添加)。因此,如果您将代码放在导航自的
中,您将无法获得预期的行为

作为一种解决方法,您可以将代码放在前面,如下所示:

Compositor _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
Visual _targetVisual = ElementCompositionPreview.GetElementVisual(this);
var animation = _compositor.CreateScalarKeyFrameAnimation();
animation.Duration = new TimeSpan(0, 0, 0, 0, 3000);
animation.InsertKeyFrame(0.0f, 1.0f);
animation.InsertKeyFrame(1.0f, 0.0f);

_targetVisual.StartAnimation("Opacity", animation);
await Task.Delay(3000);//Give some time for the animation to start
Frame.Navigate(typeof(NewPage));
因此,您将获得页面衰减的动画,我制作了一个演示,您可以参考: