我有WinUI 3应用程序,有4个元素:
App.xaml(.cs)
、MainWindow.xaml(.cs)
、LoadingPage.xaml(.cs)
和RegularContentPage.xaml(.cs)
。
我的任务是:虽然
App.xaml.cs
中的代码做了一些解决方法,但我想在LoadingPage
中显示MainWindow
。 App.xaml.cs
中的工作完成后,将MainWindow
的内容更改为RegularContentPage
。
我现在如何实现它:
App.xaml.cs
中的工作完成后,它会触发事件
public delegate void EventHandler(object sender, EventArgs args);
public event EventHandler OnAppIsReady;
OnAppIsReady?.Invoke(this, new EventArgs());
在
MainWindow
默认情况下,我显示加载页面 this.Content = new LoadingPage();
并捕获从应用程序触发的 OnAppIsReady
事件:
(Application.Current as App).viewModel.OnAppIsReady += APP_OnAppIsReady;
在
APP_OnAppIsReady
回调中,我更改了窗口的内容:
private void APP_OnAppIsReady(object sender, EventArgs args)
{
this.Content = new RegularContentPage();
}
但它抛出异常:
WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|39_0(Int32 hr)
at Microsoft.UI.Xaml.Controls.Page._IPageFactory.CreateInstance(Object baseInterface, IntPtr& innerInterface)
at Microsoft.UI.Xaml.Controls.Page..ctor()
我尝试用 ViewModel 重新处理它,同样的情况。尝试使用
Frame.Navigate()
重新设计它,但有另一个例外:
WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|39_0(Int32 hr)
at ABI.Microsoft.UI.Xaml.Controls.INavigateMethods.Navigate(IObjectReference _obj, Type sourcePageType)
at Microsoft.UI.Xaml.Controls.Frame.Navigate(Type sourcePageType)
我尝试对
APP_OnAppIsReady
回调中的 UI 执行的任何操作都会导致异常和崩溃。
我怀疑这里的问题是事件在另一个线程中触发,而不是在 UI 中触发。 所以问题是: 如何从 UI 正确捕获此类事件? 还有一个问题:有更好的方法来完成我的任务(以编程方式更改窗口的内容)吗?
我的第一个猜测是
private void APP_OnAppIsReady(object sender, EventArgs args)
{
this.Content = new RegularContentPage();
}
不在主线程(UI 线程)上运行。在这种情况下,您可以使用
Page
的 DispatcherQueue
来更新 UI。
private void APP_OnAppIsReady(object sender, EventArgs args)
{
this.DispatcherQueue.TryEnqueue(() =>
{
// This is run on the main thread.
this.Content = new RegularContentPage();
});
}