如何将文件嵌入程序集并访问?WPF主题资源集成问题
将XAML主题文件嵌入程序集并加载的实现方法
1. 修改项目配置(.csproj)
把原来的Content项改为EmbeddedResource,编译时主题文件会直接嵌入程序集内部,而非复制到输出目录:
<ItemGroup> <EmbeddedResource Include="assets/themes/ice_blue.xaml" /> <EmbeddedResource Include="assets/themes/sakura.xaml" /> </ItemGroup>
如果需要统一资源的逻辑路径,可通过LogicalName指定(可选):
<EmbeddedResource Include="assets/themes/sakura.xaml"> <LogicalName>assets.themes.sakura.xaml</LogicalName> </EmbeddedResource>
2. 调整代码中的资源加载逻辑
在change_Color方法里,使用程序集资源URI格式加载嵌入的资源,格式为pack://application:,,,/[程序集名称];component/[资源相对路径]:
private void change_Color(object sender, RoutedEventArgs e) { Application app = Application.Current; var resources = app.Resources.MergedDictionaries; resources.Clear(); // 替换「你的程序集名称」为项目实际的程序集名称(可在项目属性中查看) resources.Add( new ResourceDictionary{ Source = new Uri("pack://application:,,,/你的程序集名称;component/assets/themes/sakura.xaml", UriKind.Absolute) } ); }
若程序集名称与项目名称一致,可简化路径:
Source = new Uri("pack://application:,,,/assets/themes/sakura.xaml", UriKind.Absolute)
关键说明
- 原
Content Include是将文件作为外部资源复制到输出目录,EmbeddedResource则是把文件编译进程序集,完全脱离外部文件依赖。 - 路径中的
component是固定关键字,后面的路径要和文件在项目中的相对路径完全匹配。
内容的提问来源于stack exchange,提问作者imagesck
相关产品推荐
相关产品推荐

