如何以编程方式更改Win 8.1或Win 10 UWP应用程序的背景主题?

rob*_*csi 4 c# windows themes windows-phone-8.1 uwp

我有一个Windows Phone 8.1的应用程序和它的UWP版本.我想在Windows中更改应用程序时动态更改应用程序的背景.

用例将是:

  1. 启动应用程序,背景主题是黑暗的.
  2. 按手机上的主屏幕按钮
  3. 将背景主题更改为浅
  4. 回到应用程序(基本上从后台切换到它)
  5. 该应用程序的主题将自动更改为新主题

我想这样做,没有重启.我在其他应用程序中看到了这一点,所以必须以某种方式实现,但我无法弄明白.

如果需要重启,那就像解决方案B一样好.

谢谢.

Max*_*nov 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

比,你可以在页面上创建属性设置,它将返回singleton的值并将Page的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}">
Run Code Online (Sandbox Code Playgroud)