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

How to programmatically change background theme of Win 8.1 or Win 10 UWP app?

我有一个适用于 Windows Phone 8.1 的应用程序及其 UWP 版本。我想在 Windows.

中更改时动态更改应用程序的背景

用例为:

  1. 启动应用,背景主题为深色
  2. 按 phone
  3. 上的主页按钮
  4. 将背景主题更改为浅色
  5. 回到应用程序(基本上从后台切换到它)
  6. 应用程序的主题会自动更改为新主题

我希望这样完成,无需重新启动。我在其他应用程序中看到过这个,所以它一定是可行的,但我想不通。

如果需要重启,也可以作为解决方案 B。

谢谢。

使用 ThemeResource 而不是 StaticResource 颜色可能会在运行时改变:

{ThemeResource ApplicationPageBackgroundThemeBrush}

我建议创建设置单例 class 来存储 AppTheme 状态并实现 INotify属性Changed interface

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));
    }
}

然后,您可以在页面上创建 属性 设置,这将 return 单例值并将页面的 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}">

我的问题的答案是,我不需要在 app.xaml 文件中设置 App.RequestedTheme 属性 以使应用程序的主题跟随OS.

我只是认为它需要通过代码手动完成。