Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Theme in Windows 10 UWP App Programmatically

I was able to change theme using this.RequestedTheme = ElementTheme.Dark; But what I need is the whole application level, since this one only change the theme of the current page to dark.

Whenever I try this App.Current.RequestedTheme = ApplicationTheme.Dark; I always get this error

An exception of type 'System.NotSupportedException' occurred in UWPApp.exe but was not handled in user code

Is there such a way that I can change the whole application theme from Light to Dark or vice versa?

I'm using VS2015

like image 263
AlMusal Avatar asked Jan 01 '16 09:01

AlMusal


2 Answers

Updated answer with what I finally decided on.

I used a settings class that holds all of the apps settings including what theme to use. Since the theme can only be set when it starts we need to make sure to set it them. This is the code I used:

In the App.xaml.cs file:

public App()
{
    //Load settings
    AppSettings.LoadSettings();
    this.RequestedTheme = AppSettings.SelectedTheme;

    this.InitializeComponent();
}

In the App.xaml file make sure to remove this property:

    RequestedTheme="Light"

If its not removed it always default to light with no way to change it.

This way the user can choose the theme, it gets stored and used when the app starts. Just make sure to load it and apply it in the app initialization phase.

like image 169
Threezool Avatar answered Oct 13 '22 06:10

Threezool


I found another solution that worked pretty well for me. If the app has a root frame that loads the pages (which is the case by default), I could set the requested theme of that root frame to the desired value and the theme of the app got changed without restarting. The code looks like this:

// Set theme for window root.
if (Window.Current.Content is FrameworkElement frameworkElement)
{
   frameworkElement.RequestedTheme = theme;
}

I got that snippet from the Windows Template Studio GitHub repository here, so this seems to be kind of the best way to do this.

like image 39
alxnull Avatar answered Oct 13 '22 05:10

alxnull