WinUI3 C++应用如何在主窗口显示前弹出ContentDialog?
WinUI3 C++应用:主窗口显示前弹出ContentDialog报错解决
问题场景
用C++开发WinUI3应用,需根据命令行参数在主窗口显示前弹出ContentDialog。在App::OnLaunched()中编写代码时抛出异常:
Exception thrown at 0x00007FFD661100AC (KernelBase.dll) in App1.exe:
WinRT originate error - 0x80070057 : 'This element does not have a XamlRoot. Either set the XamlRoot property or add the element to a tree.'
原代码:
window = make<MainWindow>(); window.Activate(); winrt::Microsoft::UI::Xaml::Controls::ContentDialog dialog; dialog.Title(box_value(L"Modern Dialog")); dialog.Content(box_value(L"WinUI 3 ContentDialog")); dialog.CloseButtonText(L"OK"); dialog.XamlRoot(window.Content().XamlRoot()); dialog.ShowAsync();
报错原因
调用window.Activate()后,主窗口的Content元素尚未完成初始化,此时window.Content().XamlRoot()返回的对象未就绪,无法为ContentDialog提供有效的XamlRoot上下文。
解决方案
通过注册窗口的Loaded事件,在窗口内容完全加载完成后再弹出ContentDialog,确保XamlRoot已就绪:
window = make<MainWindow>(); // 注册窗口加载完成事件 window.Loaded([this](const auto&, const auto&) { winrt::Microsoft::UI::Xaml::Controls::ContentDialog dialog; dialog.Title(box_value(L"Modern Dialog")); dialog.Content(box_value(L"WinUI 3 ContentDialog")); dialog.CloseButtonText(L"OK"); dialog.XamlRoot(window.Content().XamlRoot()); // 执行异步显示,忽略返回值(如需处理关闭逻辑可保留IAsyncAction对象) auto asyncOp = dialog.ShowAsync(); }); window.Activate();
如果需要根据命令行参数决定是否弹出对话框,只需将判断逻辑加入Loaded事件回调即可:
window = make<MainWindow>(); window.Loaded([this](const auto&, const auto&) { // 示例:检查命令行参数(需自行实现参数解析逻辑) bool needShowDialog = CheckCommandLineArgs(); if (needShowDialog) { winrt::Microsoft::UI::Xaml::Controls::ContentDialog dialog; dialog.Title(box_value(L"Modern Dialog")); dialog.Content(box_value(L"WinUI 3 ContentDialog")); dialog.CloseButtonText(L"OK"); dialog.XamlRoot(window.Content().XamlRoot()); auto asyncOp = dialog.ShowAsync(); } }); window.Activate();
内容的提问来源于stack exchange,提问作者Dorel Pîslan
相关产品推荐
相关产品推荐

