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

4
我有一个适用于Windows Phone 8.1的应用程序和一个UWP版本。我想在Windows更改背景时动态更改应用程序的背景。使用情况如下:
  1. 启动应用程序,背景主题为深色。
  2. 按下手机上的主页按钮
  3. 更改背景主题为浅色
  4. 从后台切换回应用程序
  5. 应用程序的主题将自动更改为新主题
我希望它像这样完成,无需重新启动。我已经在其他应用程序中看到过这一点,所以肯定有可能,但我无法想出解决方法。
如果需要重新启动,则也可以接受作为解决方案B。
谢谢。
3个回答

5
我建议创建一个设置单例类,用于存储应用程序主题状态,并实现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,但它将具有相同的枚举值。 - Maxim Nikonov
非常感谢您提供的信息。与此同时,我发现如果我不在app.xaml文件中设置App.RequestedTheme,我会得到我想要的效果。也就是说,应用程序的主题会更改为在操作系统中设置的主题。之前我认为需要自己从代码中进行设置。但是,你们两个的回答都非常有帮助。 - robcsi
1
当我尝试这样做时,XAML 上会出现错误,指出“无效的绑定路径 'Settings.AppTheme':在类型 'MainPage' 上找不到属性 'Settings'”。 - AbsoluteSith

4

在可能会在运行时更改的颜色上使用ThemeResource代替StaticResource

{ThemeResource ApplicationPageBackgroundThemeBrush}

0
我的问题的答案是我不需要在app.xaml文件中设置App.RequestedTheme属性,以便应用程序的主题遵循操作系统的主题。我只是认为需要手动编码完成它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接