Silverlight企業級開發中,專案中會出現大量的Style資源檔,如何將這些XAML檔打包成dll,以滿足動態改變Theme的需求呢?通過參考Toolkit的源碼中有關Theme.dll
的實現方式,本文將詳細敘述這一過程:
1.創建一個Silverlight Class Library,命名為BlackColorTheme.
2.創建需要的ResourceDictionary

1059245I6-0  

這裡創建了ButtonStyle.xaml,HyperlinkButton.xaml2個檔,Build Action設置為Resource
以ButtonStyle為例,我們設置點簡單的樣式:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button" x:Key="DefaultButtonStyle">
        <Setter Property="Background" Value="Black"></Setter>        
    </Style>
    <Style TargetType="Button" BasedOn="{StaticResource DefaultButtonStyle}"/>
</ResourceDictionary>
3.創建一個Theme.xaml,將我們的樣式檔引入

105924L62-1  

Build Action仍需要設置為Resource,Theme.xaml的內容如下:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <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主題設置.
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()