为了改变风格,我做了以下事情:
- 为我想要的每种类型的主题创建一个样式表。
- 将整个项目中的所有样式引用设置为DynamicResource而不是“StaticResource”。
- 使用 ResourceDictionaries 的操作。
在此示例中,我有高、中和低质量的主题。我的样式表路径是:
- /Assets/Styles/GlobalStylesLow.xaml
- /Assets/Styles/GlobalStylesMed.xaml
- /Assets/Styles/GlobalStylesHigh.xaml
操作代码如下:
/// <summary>
/// Level of graphics quality enum.
/// </summary>
public enum GraphicsQuality
{
/// <summary>
/// Low
/// </summary>
Low = 0,
/// <summary>
/// Medium
/// </summary>
Medium = 1,
/// <summary>
/// High
/// </summary>
High = 2
}
/// <summary>
/// Sets the Application Resource Dictionaries based on selection.
/// </summary>
/// <param name="quality">The quality.</param>
/// <param name="onRedraw">The on redraw.</param>
public static void UpdateStyles(
Enums.GraphicsQuality quality = Enums.GraphicsQuality.High, Action onRedraw = null)
{
// Reset resource dictionaries
Application.Current.Resources.MergedDictionaries.Clear();
// Base style path
const string basePath = "/<project_base>;component/Assets/Styles";
// Evaluate global quality
switch (quality)
{
case Enums.GraphicsQuality.High:
LoadStyle(basePath + "/GlobalStylesHigh.xaml");
break;
case Enums.GraphicsQuality.Medium:
LoadStyle(basePath + "/GlobalStylesMed.xaml");
break;
case Enums.GraphicsQuality.Low:
LoadStyle(basePath + "/GlobalStylesLow.xaml");
break;
}
// Redraw
if (onRedraw != null)
{
onRedraw();
}
}
/// <summary>
/// Loads a specific style by Uri.
/// </summary>
/// <param name="stylePath">The style path.</param>
private static void LoadStyle(string stylePath)
{
var dic = new ResourceDictionary
{
Source = new Uri(stylePath, UriKind.Relative)
};
Application.Current.Resources.MergedDictionaries.Add(dic);
}
当存在更改样式表的条件时,请调用UpdateStyles。
注意:
onRedraw参数只是更新样式后执行的最后一个操作。在某些情况下,您可能希望通过
this.InvalidateVisual
如果您在 UI 正确更新方面遇到问题,请从 UI 中获取。