WinUI 3 C++:如何从后台线程访问UI对话框对象?
WinUI3 C++ 后台线程访问ContentDialog问题
我是Windows桌面编程、WinUI 3的新手,时隔多年重新使用C++开发,当前在Visual Studio中基于生成代码进行开发。我开发的桌面应用无需显示主窗口,但需定期弹出对话框获取用户确认,已在MainWindow.xaml中定义ContentDialog:
<Window x:Class="Consent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Consent" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center"> <ContentDialog x:Name="consentDialog" Title="Dummy Title" CloseButtonText="Dummy Close"> Dummy Content </ContentDialog> </StackPanel> </Window>
该ContentDialog在MainWindow.xaml.g.h中声明:
::winrt::Microsoft::UI::Xaml::Controls::ContentDialog _consentDialog{nullptr}; ::winrt::Microsoft::UI::Xaml::Controls::ContentDialog consentDialog() { return _consentDialog; }
在App::OnLaunched中我执行window = make<MainWindow>();但未激活窗口。后续应用在后台线程运行时,需要显示该ContentDialog。若从按钮点击事件触发,可在MainWindow.xaml.cpp的处理函数中访问UI对象,但我不知如何在后台线程中获取该ContentDialog的引用。我曾尝试从make创建的window对象中获取,但该对象并非MainWindow类型;也考虑过在MainWindow.xaml.cpp中定义窗口创建时触发的事件来保存ContentDialog引用,或直接从MainWindow.xaml.g.h中暴露该控件,但均未找到可行方法。
内容的提问来源于stack exchange,提问作者tegat
相关产品推荐
相关产品推荐

