之前的resourcedictionary主题资源替换(一)通过加载顺序来覆盖之前的主题资源,介绍了wpf框架对resourcedictionary资源的合并规则。
此篇介绍一种在编译期间,实现资源替换的方案
如下图,项目中存在俩个主题资源字典,我们想通过配置一键修改项目的主题。
首先,我们默认使用的是灰色主题
新建文件themes.props(主题设置),
并添加当前主题版本:
1 <project> 2 <propertygroup> 3 <theme>theme-red</theme> 4 </propertygroup> 5 </project>
如上,切换当前版本为红色主题
引入主题配置文件:
<import project="..\themes.props" condition="exists('..\themes.props')" />
添加资源替换:
在编译前,判断当前主题,如果为红色主题,则替换;
1 <target name="replacetheme" beforetargets="beforebuild" condition="'$(theme)' == 'theme-red'"> 2 <itemgroup> 3 <page remove="theme-normal.xaml" /> 4 <page remove="theme-red.xaml" /> 5 <page include="theme-red.xaml"> 6 <generator>msbuild:compile</generator> 7 <link>theme-normal.xaml</link> 8 </page> 9 </itemgroup> 10 </target>
替换后的主题色:
此方案,需要资源字典中的键值匹配对应,如果缺失了某个样式等资源,后续可能会有意想不到的异常哦~
如何规避?
可以下载资源字典修复工具,github地址:resourceintegritycheck
工具会将缺失的资源,从另一份资源字典中复制到此资源文件中。所以修复完成,提交代码前可以确认下,资源是否匹配当前主题。
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论