これは、テーマをサポートするアプリケーションで使用したコードのスニペットです。この例では、2つのテーマ(デフォルトとクラシックXP)があります。テーマリソースは、それぞれDefaultTheme.xamlとClassicTheme.xamlに保存されます。
これは私のApp.xamlのデフォルトコードです
<Application ...>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ArtworkResources.xaml" />
<ResourceDictionary Source="DefaultTheme.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="SwooshButton" TargetType="ButtonBase">
<!-- style setters -->
</Style>
<!-- more global styles -->
</ResourceDictionary>
</Application.Resources>
</Application>
次に、App.xamlの背後にあるコードで、テーマを変更できるようにする次のメソッドがあります。基本的には、リソースディクショナリをクリアしてから、新しいテーマでディクショナリをリロードします。
private Themes _currentTheme = Themes.Default;
public Themes CurrentTheme
{
get { return _currentTheme; }
set { _currentTheme = value; }
}
public void ChangeTheme(Themes theme)
{
if (theme != _currentTheme)
{
_currentTheme = theme;
switch (theme)
{
default:
case Themes.Default:
this.Resources.MergedDictionaries.Clear();
AddResourceDictionary("ArtworkResources.xaml");
AddResourceDictionary("DefaultTheme.xaml");
break;
case Themes.Classic:
this.Resources.MergedDictionaries.Clear();
AddResourceDictionary("ArtworkResources.xaml");
AddResourceDictionary("ClassicTheme.xaml");
break;
}
}
}
void AddResourceDictionary(string source)
{
ResourceDictionary resourceDictionary = Application.LoadComponent(new Uri(source, UriKind.Relative)) as ResourceDictionary;
this.Resources.MergedDictionaries.Add(resourceDictionary);
}
このアプローチで覚えておく必要があるのは、テーマを利用するスタイルには動的なリソースが必要になるということです。例えば:
<Window Background="{DynamicResource AppBackgroundColor}" />