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

WinUI3引用NuGet包中ResourceDictionary报错的解决咨询

WinUI3 NuGet类库ResourceDictionary集成解决方案

1. 确保资源文件的生成操作配置正确

  • 类库中所有ResourceDictionary(.xaml文件),右键选择属性,将生成操作设为Page,复制到输出目录设为如果较新则复制或始终复制。
  • 也可直接在.csproj中添加配置:
<ItemGroup>
  <Page Include="Themes\**\*.xaml" >
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <SubType>Designer</SubType>
  </Page>
</ItemGroup>

2. 修正资源路径的引用格式

WinUI3引用NuGet类库资源时,不能直接用ms-appx:///+自定义名称的路径,必须以类库程序集名称作为路径前缀,正确格式示例:

<ResourceDictionary Source="ms-appx:///Haprotec.WinUI.UI/Themes/YourResource.xaml" />

注意:这里的Haprotec.WinUI.UI是类库的程序集名称,需与csproj中AssemblyName一致(未显式设置时默认和RootNamespace相同)。

3. 调整NuGet包的.csproj配置

在现有配置基础上补充关键设置,确保资源被正确打包:

<PropertyGroup>
  <TargetFramework>net6.0-windows10.0.18362.0</TargetFramework>
  <TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
  <RootNamespace>Haprotec.WinUI.UI</RootNamespace>
  <AssemblyName>Haprotec.WinUI.UI</AssemblyName> <!-- 明确程序集名称 -->
  <RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
  <UseWinUI>true</UseWinUI>
  <WindowsPackageType>None</WindowsPackageType>
  <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  <WinUISDKReferences>false</WinUISDKReferences>
  <EnablePreviewMsixTooling>true</EnablePreviewMsixTooling>
  <GenerateLibraryLayout>true</GenerateLibraryLayout>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  <PackageIncludeAssets>all</PackageIncludeAssets> <!-- 确保所有资源被打包进NuGet -->
</PropertyGroup>

4. 清理重建与缓存处理

  • 清理类库项目,重新生成NuGet包,删除本地NuGet缓存(路径为%userprofile%\.nuget\packages下对应包的文件夹)。
  • 在引用项目中先卸载NuGet包,清理项目后重新安装,最后完整重建项目。

额外验证方案

可在类库中添加静态类,通过代码加载资源验证路径正确性:

using Microsoft.UI.Xaml;

namespace Haprotec.WinUI.UI.Themes
{
    public static class ResourceLoader
    {
        public static ResourceDictionary GetThemeResources()
        {
            var rd = new ResourceDictionary();
            rd.Source = new Uri("ms-appx:///Haprotec.WinUI.UI/Themes/YourResource.xaml");
            return rd;
        }
    }
}

在引用项目的App.xaml.cs的OnLaunched方法中调用该方法,排查是否为XAML引用的语法问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:35:20