从输出文件夹加载ResourceDictionary时,设计时能否识别其键?
解决从输出文件夹加载ResourceDictionary时设计时键不可用的问题
核心原因
pack://siteoforigin:,,,/ 指向的是应用程序运行时的输出目录,但WPF设计器在设计阶段无法正确解析这个路径——此时程序还未编译输出,设计器找不到对应的资源文件,自然无法识别资源键。
可行解决方案
1. 分离设计时与运行时资源加载路径
创建专门的设计时资源文件,让设计器读取项目内的资源,运行时再加载输出目录的资源:
- 新建
DesignTimeResources.xaml文件(放在项目根目录),内容指向项目内的资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Themes/Dark/Dark.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary>
- 将该文件的生成操作设置为
DesignDataWithDesignTimeCreatableTypes。 - 在App.xaml中通过设计时命名空间区分加载逻辑:
<Application x:Class="YourAppName.App" 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"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- 设计时加载项目内资源 --> <d:DesignData Source="DesignTimeResources.xaml" /> <!-- 运行时加载输出目录资源 --> <ResourceDictionary Source="pack://siteoforigin:,,,/Resources/Themes/Dark/Dark.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
2. 保留项目内引用+设置资源文件复制属性
让资源文件同时存在于项目内和输出目录,设计器识别项目内路径,运行时自动适配:
- 选中
Dark.xaml文件,在属性窗口设置:- 生成操作:
Resource - 复制到输出目录:
如果较新则复制
- 生成操作:
- 在App.xaml中同时添加两个路径的资源引用:
<ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Themes/Dark/Dark.xaml" /> <ResourceDictionary Source="pack://siteoforigin:,,,/Resources/Themes/Dark/Dark.xaml" /> </ResourceDictionary.MergedDictionaries>
运行时WPF会自动处理重复资源,不会产生冲突,设计器则能正常识别项目内的资源键。
3. 代码动态加载运行时资源
App.xaml中仅保留项目内资源供设计器使用,运行时通过代码加载输出目录的资源:
- App.xaml中只添加项目内资源引用:
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Themes/Dark/Dark.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
- 在App.xaml.cs的
OnStartup方法中动态加载运行时资源:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var runtimeDict = new ResourceDictionary(); runtimeDict.Source = new Uri("pack://siteoforigin:,,,/Resources/Themes/Dark/Dark.xaml", UriKind.Absolute); Application.Current.Resources.MergedDictionaries.Add(runtimeDict); }
内容的提问来源于stack exchange,提问作者nistrar
相关产品推荐
相关产品推荐

