我正在WinUI3上开发一个桌面应用程序.我的任务是在TextBlock上播放褪色动画(平滑地将不透明度降低到0),然后执行一些操作(例如,更改文本),然后在相同的TextBlock上播放外观动画(平滑地将不透明度增加到1).我需要按这个顺序做这些步骤,但我遇到了麻烦.

// The code for creating and setting up animations has been omitted for brevity.

myAnimation1.InsertKeyFrame(0, 1);
myAnimation1.InsertKeyFrame(1, 0);
_TextBlock.StartAnimation(myAnimation1);

_TextBlock.Inlines.Clear();
_TextBlock.Inlines.Add(GetTextInline(phrase));

myAnimation2.InsertKeyFrame(0, 1);
myAnimation2.InsertKeyFrame(1, 0);
_TextBlock.StartAnimation(myAnimation2);

在这种情况下,只要播放第一个动画,文本就会立即更改,然后其流畅外观也会随之发生变化.换句话说,第一个动画不会播放.她没能挺过来.之前,我在WPF工作,有一个特殊的事件,在动画结束后触发,多亏了它,才有可能建立动画链.但在WinUI3中,我没有发现这样的事件.如果有人知道怎么做,请写信给我.然而,我并没有放弃,并决定以这种方式使用任务类来模拟这种行为.

// The code for creating and setting up animations has been omitted for brevity.

Task task1 = new Task(() =>
{
    myAnimation1.InsertKeyFrame(0, 1);
    myAnimation1.InsertKeyFrame(1, 0);
    _TextBlock.StartAnimation(myAnimation1);
});
Task task2 = task1.ContinueWith((Task task) =>
{
    _TextBlock.Inlines.Clear();
    _TextBlock.Inlines.Add(GetTextInline(phrase));
});
Task task3 = task2.ContinueWith((Task task) =>
{
    myAnimation2.InsertKeyFrame(0, 1);
    myAnimation2.InsertKeyFrame(1, 0);
    _TextBlock.StartAnimation(myAnimation2);
});

task1.Start();
task3.Wait();

但是这段代码在task3.Wait();"System.AggregateException:"行结束时出现了一个或多个错误.(应用程序访问与另一个线程相关的接口.(0x8001010E(RPC_E_WROR_THREAD)""

我试图删除这一行,但这三个任务根本没有运行.目前,我已经没有办法解决这个问题,并实现我心中的 idea .但我相信有一个解决方案,因为这个框架有很多处理动画的可能性.请帮帮我.

推荐答案

该错误意味着您正在对不是theUI线程的线程调用UI技术.

您可以使用ScopedBatch来完成此操作,使用扩展方法,如下所示:

public static CompositionScopedBatch RunScopedBatch(
    this Compositor compositor,
    Action action,
    Action onCompleted = null,
    CompositionBatchTypes types = CompositionBatchTypes.Animation)
{
    if (compositor == null)
        throw new ArgumentNullException(nameof(compositor));

    if (action == null)
        throw new ArgumentNullException(nameof(action));

    var batch = compositor.CreateScopedBatch(types);
    if (onCompleted != null)
    {
        // note: if Completed finishes too soon
        // it means there was an exception, problem, etc.
        batch.Completed += (s, e) => onCompleted();
    }

    try
    {
        action();
    }
    finally
    {
        batch.End();
    }
    return batch;
}

Csharp相关问答推荐

如何使用C#中的图形API更新用户配置文件图像

为什么C#Bigbit不总是相同的比特长度?

如何注销Microsoft帐户?

从c#列表中删除额外的对象&对象&>从ASP.NET WebForm返回json响应

如何在C#中从正则表达式中匹配一些数字但排除一些常量(也是数字)

由于POST中的应用程序/JWT,出现不支持的内容类型异常

在使用Audit.NET的AuditTrail实现中,如何逐月将数据摄取到AzureTableStorage?

NET8 Maui&;iOS:AppCenter崩溃错误

为什么@rendermode Interactive Auto不能在.NET 8.0 Blazor中运行?

带有列表参数的表达式树

C#动态设置ServerReport报表参数

Postgres ENUM类型在第一次运行时对Dapper不可见

如何将%{v_扩展}转换为%{v_扩展}>>

如何从Azure函数使用Graph API(SDK 5.35)中的[FindMeetingTimes]

使用C#12中的主构造函数进行空判断

Cmd中的&ping.end()";有时会失败,而";ping";总是有效

反序列化我以前使用System.Text.Json序列化的文件时出现异常

为什么C#中的类型别名不能在另一个别名中使用?

客户端/服务器RPC如何处理全局变量?

我是否以错误的方式使用了异步延迟初始化?