【MAUI Blazor踩坑日记】6.mac标题栏颜色修改

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://www.cnblogs.com/Yu-Core/p/17365766.html

MAUI中mac的标题栏颜色默认是灰白色的,有一点丑

如果我们想要自定义颜色,并且在运行时也能更改颜色,该怎么办呢

万幸从一个GitHub库中借鉴到了办法 https://github.com/BenBtg/MauiMacToolBar 这个库是自定义标题栏,如果你想自定义标题栏,而不仅仅是改变颜色,可以直接去看这个库。

第一步

Platforms/MacCatalyst文件夹下添加MacTitleBar.cs

#nullable disable
#pragma warning disable CA1416
    public static class MacTitleBar
    {
        public static void SetTitleBarColorForMac(Color backgroundColor, Color foregroundColor)
        {
            var res = Application.Current.Resources;
            res["PageBackgroundColor"] = backgroundColor;
            res["PrimaryTextColor"] = foregroundColor;
        }

        public static void InitTitleBarForMac(object sender, EventArgs e)
        {
#if MACCATALYST14_2_OR_GREATER
            var window = sender as Window;
            var uiWindow = window.Handler.PlatformView as UIKit.UIWindow;

            if (uiWindow != null)
            {
                uiWindow.WindowScene.Titlebar.TitleVisibility = UIKit.UITitlebarTitleVisibility.Hidden;
            }
#endif
        }
    }

第二步

修改App.xaml.cs

protected override Window CreateWindow(IActivationState? activationState)
        {
            Window window = base.CreateWindow(activationState);

#if MACCATALYST
            window.Created += MacTitleBar.InitTitleBarForMac;
#endif
            return window;
        }

调用

#if MACCATALYST
            var backgroundColor = Colors.White;
            var foreColor = Colors.Black;
            MacTitleBar.SetTitleBarColorForMac(backgroundColor, foreColor);
#endif

实际上,在这个uiWindow.WindowScene.Titlebar.TitleVisibility = UIKit.UITitlebarTitleVisibility.Hidden;生效之后,mac的标题栏就会显示App.xaml中<Color x:Key="PageBackgroundColor">#fff</Color>的颜色,所以我们更改PageBackgroundColor的颜色,就能改变标题栏颜色