可以使用WPF主题,包括可以在运行时改变应用多种皮肤?
-
20-08-2019 - |
题
WPF允许控制库来为不同的系统提供的主题不同资源字典,基本上允许应用程序相匹配的操作系统的选择的视觉主题(航空,露娜等)。
我不知道是否我可以包括与我的应用程序的多个主题资源字典和利用的框架内现有的一些主题支持。这应该适用于我自己的主题名称,最好允许用户更改主题和应用程序运行时的所以皮肤的外观。即使这是只是一个配置设置,它仍然会感到很有趣。
解决方案
下面是我在我的应用程序支持的主题化使用的代码片段。在这个例子中,我有两个主题(默认和经典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}" />
其他提示
我不知道的框架中这样做的方式,但如果你的风格,每一个可改变自己的控制,你可以做到这一点。
的理论是使风格DynamicResource
然后基于针对不同样式的用户配置加载ResourcesDictionary
。
这里是具有一个例子的制品。
不隶属于 StackOverflow