我建議創建的設置將存儲AppTheme狀態並實現INotifyPropertyChanged接口
public class Settings : INotifyPropertyChanged
{
private static volatile Settings instance;
private static readonly object SyncRoot = new object();
private ElementTheme appTheme;
private Settings()
{
this.appTheme = ApplicationData.Current.LocalSettings.Values.ContainsKey("AppTheme")
? (ElementTheme)ApplicationData.Current.LocalSettings.Values["AppTheme"]
: ElementTheme.Default;
}
public static Settings Instance
{
get
{
if (instance != null)
{
return instance;
}
lock (SyncRoot)
{
if (instance == null)
{
instance = new Settings();
}
}
return instance;
}
}
public ElementTheme AppTheme
{
get
{
return this.appTheme;
}
set
{
ApplicationData.Current.LocalSettings.Values["AppTheme"] = (int)value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
不是單例類,您可以在頁面上創建屬性設置,該屬性設置將返回單身人士的價值並將頁面的RequestedTheme綁定到AppTheme屬性
<Page
x:Class="SamplePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
RequestedTheme="{x:Bind Settings.AppTheme, Mode=OneWay}">
當應用程序啓動時,如何獲取Windows主題(黑暗或光明),以便我可以將該值設置爲Settings.Apptheme? – robcsi
在開始時,您可以使用RequestedTheme屬性的應用程序,它將是ApplicationTheme類型而不是ElementTheme,但它將具有相同的枚舉值 –
非常感謝您的信息。在此期間我發現,如果我沒有在app.xaml文件中設置App.RequestedTheme,我就會得到我正在尋找的東西。也就是說,應用程序的主題將更改爲在OS中設置的主題。之前我曾經想過,我需要自己從代碼中做到這一點。儘管如此,你的回答都很有幫助。 – robcsi