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

设置ResourceDictionary的Source属性抛出异常,请问问题出在哪?

问题描述

复现问题的代码:

ResourceDictionary dict = new ResourceDictionary();
Uri source = new(@"pack://application:,,,/Resources/ResourceDictionary1.xaml", UriKind.Absolute);
dict.Source = source;

执行时抛出异常:

Cannot locate resource from 'pack://application:,,,/Resources/ResourceDictionary1.xaml'.
Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll
Unknown error

ResourceDictionary1.xaml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:EEA_Converter_Tool.Resources"
    x:Name="TestDict"
>
</ResourceDictionary>

文件实际路径为ProjectFolder/Resources/ResourceDictionary1.xaml,确认文件存在且路径正确,请问哪里操作出错了?


解决方法

按以下方向逐一排查:

  1. 检查文件生成属性
    右键ResourceDictionary1.xaml文件 → 属性,确保生成操作设置为Resource,复制到输出目录设置为不复制。资源会嵌入程序集,无需单独复制到输出目录。

  2. 修正URI格式(针对WinUI/UWP项目)
    如果是WinUI或UWP项目,WPF风格的pack://application:,,, URI不适用,改用UWP标准资源路径:

// 绝对路径写法
dict.Source = new Uri("ms-appx:///Resources/ResourceDictionary1.xaml");
// 相对路径写法
dict.Source = new Uri("/Resources/ResourceDictionary1.xaml", UriKind.Relative);
  1. 补充程序集名称(若资源在类库中)
    如果资源字典在单独类库中,URI需要指定程序集名称:
new Uri("pack://application:,,,/EEA_Converter_Tool;component/Resources/ResourceDictionary1.xaml", UriKind.Absolute);

其中EEA_Converter_Tool是程序集名称,component为固定关键字。

  1. 核对路径大小写
    Windows文件系统不区分大小写,但URI解析可能严格匹配,确保代码中路径的大小写和实际文件路径完全一致。

  2. 清理并重建项目
    缓存可能导致资源未正确嵌入,右键项目选择「清理」,再重新生成项目后测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:13:22