I find that Axnull's answer is most useful as it allows you to set a theme while the application is running. After more than a good working day, I was able to install the application theme on the fly and save it in memory for the next run, giving the user control using ToggleButton .
First, I created a settings class with Theme property that automatically saves the current settings:
class AppSettings { public const ElementTheme DEFAULTTHEME = ElementTheme.Light; public const ElementTheme NONDEFLTHEME = ElementTheme.Dark; const string KEY_THEME = "appColourMode"; static ApplicationDataContainer LOCALSETTINGS = ApplicationData.Current.LocalSettings; /// <summary> /// Gets or sets the current app colour setting from memory (light or dark mode). /// </summary> public static ElementTheme Theme { get { // Never set: default theme if (LOCALSETTINGS.Values[KEY_THEME] == null) { LOCALSETTINGS.Values[KEY_THEME] = (int)DEFAULTTHEME; return DEFAULTTHEME; } // Previously set to default theme else if ((int)LOCALSETTINGS.Values[KEY_THEME] == (int)DEFAULTTHEME) return DEFAULTTHEME; // Previously set to non-default theme else return NONDEFLTHEME; } set { // Error check if (value == ElementTheme.Default) throw new System.Exception("Only set the theme to light or dark mode!"); // Never set else if (LOCALSETTINGS.Values[KEY_THEME] == null) LOCALSETTINGS.Values[KEY_THEME] = (int)value; // No change else if ((int)value == (int)LOCALSETTINGS.Values[KEY_THEME]) return; // Change else LOCALSETTINGS.Values[KEY_THEME] = (int)value; } } }
Then, the following code was added to the page constructor:
public MainPage() { this.InitializeComponent();
This sets the theme according to the previous selection in the application memory and sets the corresponding switch.
The following method is called when the page loads:
/// <summary> /// Set the theme toggle to the correct position (off for the default theme, and on for the non-default). /// </summary> private void SetThemeToggle(ElementTheme theme) { if (theme == AppSettings.DEFAULTTHEME) tglAppTheme.IsOn = false; else tglAppTheme.IsOn = true; }
And this handles the switch toggle:
All of the above code is generated for the following ToggleButton switch:
<ToggleSwitch Name="tglAppTheme" Header="Theme" OffContent="Light" OnContent="Dark" IsOn="False" Toggled="ToggleSwitch_Toggled" />
This setup is quite simple and may possibly save someone from hard work.
source share