2015-11-17 30 views
4

我有一個適用於Windows Phone 8.1及其UWP版本的應用程序。我希望在Windows中更改應用程序的動態背景。如何以編程方式更改Win 8.1或Win 10 UWP應用程序的背景主題?

使用情況是:

  1. 啓動應用程序,主題背景是暗的。
  2. 按電話
  3. 更改主題背景上的主頁按鈕點亮
  4. 返回到應用程序(基本上切換到它在後臺)
  5. 應用程序的主題將自動更改爲新主題

我想這樣做,沒有重新啓動。我已經在其他應用程序中看到過,所以它必須以某種方式可能,但我無法弄清楚。

如果需要重新啓動,這是沒有過的溶液B.

感謝。

回答

5

我建議創建的設置將存儲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}"> 
+0

當應用程序啓動時,如何獲取Windows主題(黑暗或光明),以便我可以將該值設置爲Settings.Apptheme? – robcsi

+0

在開始時,您可以使用RequestedTheme屬性的應用程序,它將是ApplicationTheme類型而不是ElementTheme,但它將具有相同的枚舉值 –

+0

非常感謝您的信息。在此期間我發現,如果我沒有在app.xaml文件中設置App.RequestedTheme,我就會得到我正在尋找的東西。也就是說,應用程序的主題將更改爲在OS中設置的主題。之前我曾經想過,我需要自己從代碼中做到這一點。儘管如此,你的回答都很有幫助。 – robcsi

3

使用ThemeResource而不是StaticResource對可能在運行時改變顏色:

{ThemeResource ApplicationPageBackgroundThemeBrush} 
0

我的問題的答案是,我不需要在app.xaml文件中設置App.RequestedTheme屬性,以便讓應用程序的主題跟隨其中一個操作系統。

我只是認爲它需要由代碼手動完成。

相關問題