我发现axnull 的回答最有帮助,因为它允许在应用程序运行时设置主题。经过一个下午的工作后,我能够即时设置应用程序的主题并将其保存在内存中以供下次启动,通过ToggleButton 为用户提供控制权。
首先,我创建了一个带有Theme 属性的设置类,它会自动存储当前设置:
AppSettings.cs
class AppSettings
{
public const ElementTheme DEFAULTTHEME = ElementTheme.Light;
public const ElementTheme NONDEFLTHEME = ElementTheme.Dark;
const string KEY_THEME = "appColourMode";
static ApplicationDataContainer LOCALSETTINGS = ApplicationData.Current.LocalSettings;
/// <summary>
/// Gets or sets the current app colour setting from memory (light or dark mode).
/// </summary>
public static ElementTheme Theme {
get {
// Never set: default theme
if (LOCALSETTINGS.Values[KEY_THEME] == null)
{
LOCALSETTINGS.Values[KEY_THEME] = (int)DEFAULTTHEME;
return DEFAULTTHEME;
}
// Previously set to default theme
else if ((int)LOCALSETTINGS.Values[KEY_THEME] == (int)DEFAULTTHEME)
return DEFAULTTHEME;
// Previously set to non-default theme
else
return NONDEFLTHEME;
}
set {
// Error check
if (value == ElementTheme.Default)
throw new System.Exception("Only set the theme to light or dark mode!");
// Never set
else if (LOCALSETTINGS.Values[KEY_THEME] == null)
LOCALSETTINGS.Values[KEY_THEME] = (int)value;
// No change
else if ((int)value == (int)LOCALSETTINGS.Values[KEY_THEME])
return;
// Change
else
LOCALSETTINGS.Values[KEY_THEME] = (int)value;
}
}
}
然后,在页面构造函数中,添加如下代码:
MainPage.xaml.cs
public MainPage()
{
this.InitializeComponent();
// Set theme for window root
FrameworkElement root = (FrameworkElement)Window.Current.Content;
root.RequestedTheme = AppSettings.Theme;
SetThemeToggle(AppSettings.Theme);
}
这会根据应用内存中的先前选择设置主题,并将切换设置为匹配。
页面加载时会调用以下方法:
MainPage.xaml.cs
/// <summary>
/// Set the theme toggle to the correct position (off for the default theme, and on for the non-default).
/// </summary>
private void SetThemeToggle(ElementTheme theme)
{
if (theme == AppSettings.DEFAULTTHEME)
tglAppTheme.IsOn = false;
else
tglAppTheme.IsOn = true;
}
这会处理切换的切换:
MainPage.xaml.cs
/// <summary>
/// Switch the app's theme between light mode and dark mode, and save that setting.
/// </summary>
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
FrameworkElement window = (FrameworkElement)Window.Current.Content;
if (((ToggleSwitch)sender).IsOn)
{
AppSettings.Theme = AppSettings.NONDEFLTHEME;
window.RequestedTheme = AppSettings.NONDEFLTHEME;
}
else
{
AppSettings.Theme = AppSettings.DEFAULTTHEME;
window.RequestedTheme = AppSettings.DEFAULTTHEME;
}
}
以上所有代码都是为以下ToggleButton 开关创建的:
MainPage.xaml
<ToggleSwitch Name="tglAppTheme"
Header="Theme"
OffContent="Light"
OnContent="Dark"
IsOn="False"
Toggled="ToggleSwitch_Toggled" />
此设置非常简单,有望为某人省去繁重的工作。