You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF新旧项目集成WinUI3控件遇资源未找到问题求助

WPF集成WinUI3控件的错误修复方案

问题根源分析

当前实现存在三个核心错误:

  1. 命名空间语法错误:WPF XAML不支持UWP/WinUI的using:命名空间语法,必须使用clr-namespace+assembly的WPF标准引用方式。
  2. 资源加载方式错误:XamlControlsResources需要作为合并字典添加到WPF的资源体系中,而非单独定义为资源项。
  3. 控件承载方式错误:WinUI3控件无法直接在WPF窗口中渲染,必须通过WindowsXamlHost控件作为宿主承载。

正确实现步骤及代码

1. 确认必备NuGet包

除了Microsoft.WindowsAppSDK,还需安装Microsoft.Toolkit.Wpf.UI.XamlHost包(提供WinUI控件的WPF宿主)。

2. 修正App.xaml资源配置

<Application x:Class="WpfApp2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:winui="clr-namespace:Microsoft.UI.Xaml.Controls;assembly=Microsoft.WinUI"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- 合并WinUI3控件资源到WPF资源字典 -->
                <winui:XamlControlsResources />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

3. 修正MainWindow.xaml的控件承载

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:xamlhost="clr-namespace:Microsoft.Toolkit.Wpf.UI.XamlHost;assembly=Microsoft.Toolkit.Wpf.UI.XamlHost"
        xmlns:muxc="clr-namespace:Microsoft.UI.Xaml.Controls;assembly=Microsoft.WinUI"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <!-- 使用WindowsXamlHost承载WinUI3 TreeView控件 -->
    <xamlhost:WindowsXamlHost InitialTypeName="Microsoft.UI.Xaml.Controls.TreeView">
        <xamlhost:WindowsXamlHost.Child>
            <muxc:TreeView>
                <muxc:TreeView.RootNodes>
                    <muxc:TreeViewNode Content="Flavors">
                        <muxc:TreeViewNode.Children>
                            <muxc:TreeViewNode Content="Vanilla"/>
                        </muxc:TreeViewNode.Children>
                    </muxc:TreeViewNode>
                </muxc:TreeView.RootNodes>
            </muxc:TreeView>
        </xamlhost:WindowsXamlHost.Child>
    </xamlhost:WindowsXamlHost>
</Window>

额外注意事项

  • 项目目标框架需设置为.NET 6或更高版本,WinAppSDK不兼容.NET Framework(.NET 5可支持但推荐.NET 6+)。
  • 执行清理解决方案→重建解决方案操作,避免缓存导致的资源加载异常。
  • 检查Visual Studio是否已安装“Windows App SDK”组件,可通过Visual Studio安装程序的“单个组件”列表确认。

内容的提问来源于stack exchange,提问作者karthiga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:40:33