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

标签 c# xaml animation uwp

我已经创建了一个继承自 Page 的自定义控件,以对 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);
    }
}

当我运行代码时,行 _targetVisual.StartAnimation("Opacity", animation) 引发 System.UnauthorizedAccessException。我被告知“不允许调用者对此对象执行此操作”。我做错了什么?

最佳答案

When I run the code, the line _targetVisual.StartAnimation("Opacity", animation) lifts a System.UnauthorizedAccessException. i'm told that "The caller is not allowed to perform this operation on this object".

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

ElementCompositionPreview _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

Page.OnNavigatingFrom在导航之前引发,但我们不能延迟以阻止页面导航。当我们使用 Task.Delay 时,我们需要一个 await 让它同步工作。但是会使整个函数异步运行(async会在使用await的时候加入)。因此,如果您将代码放在 OnNavigatingFrom 中,您将不会获得预期的行为

作为解决方法,您可以将代码放在 Frame.Navigate 之前如下所示:

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

这样就得到一个页面淡出的动画,我做了一个demo,可以引用:CustomPageSample .

关于c# - 自定义页面控件中的合成动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542689/

相关文章:

c# - 在 C# 中创建一组静态常量变量

c# - 获取 List<string> 的一部分

c# - 仅使用 access_token 使用 Twitter API 进行简单查询

c# - Windows 10 开发 : How to refresh ListView whenever there is a change in the items inside ListView?

XAML 绑定(bind)字符串连接

html - 减慢css3中的动画

c# - 在 outlook 中显示 Outlook 约会扩展属性

xaml - 更改 VisualState 中的值

javascript - meteor js未渲染的钩子(Hook)?

ios - Swift:removefromSuperview 移除约束