很多时候我们希望复用WPF中的样式,而通过复制一长串样式代码至XAML中的静态资源显得极为不雅,导致代码不易于管理。
而想要改变这种模式有两种方式:(1)新增“资源字典”项目,将样式代码写入该文件中,使用时只需引用该文件即可;(2)将上述的“资源字典”放到一个类库项目中,生成程序集,其他项目想要使用时需引用该程序集,然后添加对应的样式文件路径即可。
方法1:
在生成exe的程序中,需要设定关键词(Key),控件引用时加 Resources属性
方法2:
<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/Windows.Theme;component/Theme.xaml" /> <ResourceDictionary Source="/Windows.WPFStyle;component/TextBoxTipStyle.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>
图中显示为引用“Windows.Theme”程序集,样式文件名为“AppButtonStyle.xaml”,而Button所引用的具体样式为“AppColorChange”。