Silverlight企业级开发中,项目中会出现大量的Style资源文件,如何将这些XAML文件打包成dll,以满足动态改变Theme的需求呢?通过参考Toolkit的源码中有关Theme.dll
的实现方式,本文将详细叙述这一过程:
1.创建一个Silverlight Class Library,命名为BlackColorTheme.
2.创建需要的ResourceDictionary
这里创建了ButtonStyle.xaml,HyperlinkButton.xaml2个文件,Build Action设置为Resource
以ButtonStyle为例,我们设置点简单的样式:
<ResourceDictionary xmlns="" xmlns:x=""> <Style TargetType="Button" x:Key="DefaultButtonStyle"> <Setter Property="Background" Value="Black">Setter> Style> <Style TargetType="Button" BasedOn="{StaticResource DefaultButtonStyle}"/>ResourceDictionary>
3.创建一个Theme.xaml,将我们的样式文件引入
Build Action仍需要设置为Resource,Theme.xaml的内容如下:
<ResourceDictionary xmlns="" xmlns:x=""> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/BlackColorTheme;component/ButtonStyle.xaml">ResourceDictionary> <ResourceDictionary Source="/BlackColorTheme;component/HyperlinkButton.xaml">ResourceDictionary> ResourceDictionary.MergedDictionaries>ResourceDictionary>
4.创建一个BlackColorTheme.cs文件,继承System.Windows.Controls.Theming.Toolkit.Theme类
public class BlackColorTheme : Theme{ public static Uri ThemeResourceUri = new Uri("/BlackColorTheme;component/Theme.xaml", UriKind.RelativeOrAbsolute); public BlackColorTheme() : base(ThemeResourceUri) { } public static bool GetIsApplicationTheme(Application app) { return GetApplicationThemeUri(app) == ThemeResourceUri; } public static void SetIsApplicationTheme(Application app, bool value) { SetApplicationThemeUri(app, ThemeResourceUri); } }
到这一步,我们已经创建完成了将松散的XAML文件打包成dll,具体如何使用创建好的主题,如果不熟悉这方面的操作,请参考我的这篇文章:Silverlight主题设置.