You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改.NET MAUI Blazor Windows应用的窗口背景色?

解决.NET MAUI Blazor Windows应用启动时窗口背景闪烁问题

针对你遇到的启动时窗口背景与WebView主题冲突导致的闪烁问题,可以通过Windows平台特定代码直接设置窗口背景色,绕过MAUI页面加载延迟的问题,具体实现如下:

方法一:在Windows项目的App.xaml.cs中修改窗口背景

打开Platforms/Windows/App.xaml.cs,找到OnLaunched方法,添加窗口背景设置逻辑:

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);

    var currentWindow = Application.Current.Windows.FirstOrDefault();
    if (currentWindow?.Handler?.PlatformView is Microsoft.UI.Xaml.Window nativeWindow)
    {
        // 设置与WebView主题一致的背景色(示例为#e2f0fc对应的ARGB值)
        nativeWindow.Content.Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(
            Microsoft.UI.Colors.FromArgb(255, 226, 240, 252)
        );
    }
}

方法二:在MauiProgram.cs中配置生命周期事件

也可以在跨平台配置层中针对Windows平台设置窗口初始化逻辑:

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureLifecycleEvents(events =>
    {
#if WINDOWS
        events.AddWindows(winBuilder =>
        {
            winBuilder.OnWindowCreated(window =>
            {
                window.Content.Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(
                    Microsoft.UI.Colors.FromArgb(255, 226, 240, 252)
                );
            });
        });
#endif
    });

原理说明

你之前设置ContentPage.BackgroundColor属于MAUI页面层级的配置,该设置要等到页面加载完成后才会生效,无法覆盖启动初期Windows系统默认的色调背景。而上述两种方法直接操作Windows原生窗口对象,在窗口创建阶段就完成背景色设置,从根源上避免了启动时的背景闪烁问题。

内容的提问来源于stack exchange,提问作者Zrylx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:45:58