How to change uwp app title bar color when Windows 10 change from dark theme to light and vice versa?

926 Views Asked by At

I have an app for test, with 3 buttons:

  • one for change title bar color to white
  • one for change title bar color to black
  • one for let the app title bar free to follow the Windows 10 theme color for its app title bar

Those first two buttons are ok and working, but the last one I don't know how to implement and where to put methods if necessary. I'd like, please, any help, tip or even a whole solution for the problem. Thank you in advance. PS: would be great if title bar color can follow dark, light and even high contrast colors.

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace App7
{
    public sealed partial class MainPage : Page
    {
        Windows.UI.ViewManagement.ApplicationViewTitleBar titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            titleBar.BackgroundColor = Windows.UI.Colors.White;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            titleBar.BackgroundColor = Windows.UI.Colors.Black;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //Title bar must be free to change its own colour accord/when/same time Windows theme change
            //How can I do that?
            //Where the code/methods goes?
        }
    }
}
1

There are 1 best solutions below

0
Roy Li - MSFT On

You could handle the ColorValuesChanged Event of the UISettings Class. This event will happen when the Windows theme color is changed. You could get the current color of the Windows theme using UISettings.GetColorValue() to check if it is in Dark mode or Light mode. Then you could change the title bar color as you want.

Here is the code:

public Windows.UI.ViewManagement.UISettings uiSettings { get; set; }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        uiSettings = new Windows.UI.ViewManagement.UISettings();
        uiSettings.ColorValuesChanged += UiSettings_ColorValuesChanged;

        // if you want to stop this.
        //uiSettings.ColorValuesChanged -= UiSettings_ColorValuesChanged;
    }

    private void UiSettings_ColorValuesChanged(Windows.UI.ViewManagement.UISettings sender, object args)
    {
        // happens when the windows theme is changed.
        // The color you get is either black(#FF000000) for dark theme or white(#FFFFFFFF) for light theme.
        Color backgroundcolor = uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Background);
        // change titlebar color.
        Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar.BackgroundColor = backgroundcolor;
    }