Search code examples
c#windows-runtimemauimaui-windows

How to change color title bar in MAUI?


I want to change title bar color like theme color.

title bar

I get theme color but i dont know how to change the color. I try

#if WINDOWS
 var uiSettings = new Windows.UI.ViewManagement.UISettings();
 var color = uiSettings.GetColorValue(UIColorType.Accent);

var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
    var titleBar = appView.TitleBar;
    titleBar.BackgroundColor = color;
#endif

I get exception System.Runtime.InteropServices.COMException: 'Element not found. Sorry for my bad english.


Solution

  • According to the official document about Title bar customization in the WinUI3, you should use the WinUI3's api to do that. The code you used is for the uwp not the winui3.

    So you can try the following code:

    #if WINDOWS
                var uiSettings = new Windows.UI.ViewManagement.UISettings();
                var color = uiSettings.GetColorValue(UIColorType.Accent);
                Microsoft.UI.Xaml.Window window = (Microsoft.UI.Xaml.Window)App.Current.Windows.First<Window>().Handler.PlatformView;
                //get the current window on the windows platform
                IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
                Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
                Microsoft.UI.Windowing.AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
                Microsoft.UI.Windowing.AppWindowTitleBar titlebar = appWindow.TitleBar;
               //titlebar.ExtendsContentIntoTitleBar = true;
               // in the official document, this line is needed, but when I used it, the background color didn't change
                titlebar.BackgroundColor = color;
    #endif
    

    I refered to this issue about customizing the title bar in the maui. It may provide you more ideas.