Win32中WinUI3的DesktopWindowXamlSource转IDesktopWindowXamlSourceNative失败(E_NOINTERFACE)
解决WinUI3 XAML Islands中DesktopWindowXamlSource转换为互操作接口失败的问题
核心问题原因
你误用了UWP XAML Islands的互操作接口IDesktopWindowXamlSourceNative,而WinUI3的DesktopWindowXamlSource对应的是专属的IDesktopWindowXamlSourceNative2接口,同时缺少必要的头文件和库链接配置。
具体修复步骤
替换头文件
将代码中的<windows.ui.xaml.hosting.desktopwindowxamlsource.h>替换为WinUI3专属的互操作头文件:#include <microsoft.ui.xaml.hosting.desktopwindowxamlsource.h>添加库链接
在代码中添加WinUI3库的链接指令,或者在项目属性的「链接器->输入->附加依赖项」中添加Microsoft.ui.xaml.lib:#pragma comment(lib, "Microsoft.ui.xaml.lib")替换互操作接口类型
将接口转换代码中的IDesktopWindowXamlSourceNative改为IDesktopWindowXamlSourceNative2:auto interop = desktopWindowXamlSource.as<IDesktopWindowXamlSourceNative2>();验证Windows SDK版本
确保项目的Windows SDK版本设置为**10.0.19041.0(Windows 10 2004)**或更高版本,WinUI3对最低SDK版本有要求。
修复后的完整代码示例
#include "framework.h" #include "WinUI3XamlIslandsWin32.h" #include <winrt/Microsoft.UI.Dispatching.h> #include <winrt/Microsoft.UI.Xaml.Hosting.h> #include <microsoft.ui.xaml.hosting.desktopwindowxamlsource.h> #include <cassert> #pragma comment(lib, "Microsoft.ui.xaml.lib") int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { winrt::init_apartment(winrt::apartment_type::single_threaded); auto dispatcherQueueController = winrt::Microsoft::UI::Dispatching::DispatcherQueueController::CreateOnCurrentThread(); auto windowsXamlManager = winrt::Microsoft::UI::Xaml::Hosting::WindowsXamlManager::InitializeForCurrentThread(); winrt::Microsoft::UI::Xaml::Hosting::DesktopWindowXamlSource desktopWindowXamlSource; auto interop = desktopWindowXamlSource.as<IDesktopWindowXamlSourceNative2>(); assert(interop != nullptr); // 后续可以调用interop->AttachToWindow(hWnd)将XAML源附加到Win32窗口 return EXIT_SUCCESS; }
内容的提问来源于stack exchange,提问作者Litherum
相关产品推荐
相关产品推荐

