WPF 覆盖在按钮完成后才会激活

WPF Overlay does not activate until after button has finished

我有一个使用 Caliburn Micro 的小示例 WPF 应用程序。在其中,我有一个矩形叠加层,上面写着正在加载。我希望它在加载大型任务时出现,但是直到方法完成后它才会出现。我已经尝试使用 Dispatch 以及其他建议,但是在按钮方法完成之前没有任何效果。下面是我当前的例子

  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

仅在 LongMethod() 完成后才会显示叠加层 运行。有没有办法让它在方法运行之前显示?

您应该使用 TAP(基于任务的异步编程),它与此类用例集成得很好。

async void TheActionButton() 
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);

    await LongMethod();

    IsLoadingMessageVisible = false;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
}

注意:以这种方式实现你的IsLoadingMessageVisible,这样你就不需要每次设置[=19=时都调用NotifyOfPropertyChange() ].

您还没有发布 LongMethod 的实现,所以无法说出它实际做了什么,但我猜它不是作为异步实现的,而是阻塞了 UI 线程.

您可以尝试使用 Task:

在后台线程上执行它
public async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
    await Task.Run(LongMethod);
}

方法不会自动异步,因为它 returns 是 TaskTask<T> 并且可以等待。