How to programmatically change the background theme of a Win 8.1 or Win 10 UWP application?

I have an application for Windows Phone 8.1 and its UWP version. I would like to dynamically change the background of applications when it is changed in Windows.

Use Case:

  • Launch the application, the dark theme is dark.
  • Press the home button on the phone
  • Change the background theme for lighting
  • Go back to the application (basically switch to it from the background)
  • The theme of the application will automatically change to a new theme.

I would like it to be done this way without a reboot. I have seen this in other applications, so it should be possible somehow, but I can not understand.

If a reboot is required, this is as good as solution B.

Thanks.

+4
3

singleton class, 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));
    }
}

, singleton RequestedTheme of page 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}">
+5

ThemeResource StaticResource , :

{ThemeResource ApplicationPageBackgroundThemeBrush}
+3

The answer to my question is that I do not need to set the App.RequestedTheme property in the app.xaml file so that the application theme matches one of the OS.

I just thought it had to be done manually using code.

0
source

Source: https://habr.com/ru/post/1616178/


All Articles