在运行时更改主题

时间:2010-12-07 12:18:21

标签: c# silverlight xaml themes silverlight-jetpack-theme

我使用JetPack主题并从App.xaml设置它:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/Styles/Brushes.xaml"/>
            <ResourceDictionary Source="Assets/Styles/Fonts.xaml"/>
            <ResourceDictionary Source="Assets/Styles/CoreStyles.xaml"/>
            <ResourceDictionary Source="Assets/Styles/Styles.xaml"/>
            <ResourceDictionary Source="Assets/Styles/SdkStyles.xaml"/>
            <ResourceDictionary Source="Assets/Styles/ToolkitStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

如何在代码隐藏中设置主题并在运行时更改主题?

1 个答案:

答案 0 :(得分:1)

Silverlight Toolkit基础Theme控件支持在运行时更改主题。不幸的是,像JetPack主题这样的应用主题不是Toolkit主题(问问Microsoft为什么)。所以你必须自己转换它们。查看工具包主题来源有助于我们弄清楚如何:

public class JetPackTheme : Theme
{
    private static Uri ThemeResourceUri = new Uri("/MyComponent;component/JetPackTheme.xaml", UriKind.Relative);

    public JetPackTheme() : base(ThemeResourceUri) { }

    public static bool GetIsApplicationTheme(Application app)
    {
        return GetApplicationThemeUri(app) == ThemeResourceUri;
    }

    public static void SetIsApplicationTheme(Application app, bool value)
    {
        SetApplicationThemeUri(app, ThemeResourceUri);
    }
}

现在,假设您的资源位于名为 JetPackTheme 的文件夹中,此处为 JetPackTheme.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/Brushes.xaml"/>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/Fonts.xaml"/>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/CoreStyles.xaml"/>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/Styles.xaml"/>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/SdkStyles.xaml"/>
        <ResourceDictionary Source="/MyComponent;component/JetPackTheme/ToolkitStyles.xaml"/>    
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

现在您应该可以在应用程序中使用 JetPackTheme 控件:

<myCmp:JetPackTheme x:Name="myTheme">
    <SomeNeatStuff>
        ...
    </SomeNeatStuff>
</myCmp:JetPackTheme>

要在运行时更改主题,您只需执行

即可
myTheme.ThemeUri = new Uri("Path/To/The/Theme.xaml", UriKind.RelativeOrAbsoluteOrWhatever);