Search code examples
blazormauimaui-blazorblazor-hybrid

Blazor Hybrid unknown Margin / padding


hi i build a dotnet maui hybrid app with blazor web view and razor components

i try to make the blazor web view fill the screen and status bar white but i get a small gap on the top of the page and i dont know how to solv it

here is the xaml page

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
        xmlns:local="clr-namespace:BNext.NativeClient"
        xmlns:pages="clr-namespace:BNext.NativeClient.Components.Pages"
        xmlns:sharedPages="clr- 
 namespace:BNext.GuiShared.Pages;assembly=BNext.GuiShared"
        x:Class="BNext.NativeClient.MainPage"
        BackgroundColor="{DynamicResource PageBackgroundColor}"
        Padding="0">

<ContentPage.Behaviors>
    <toolkit:StatusBarBehavior StatusBarColor="White" StatusBarStyle="DarkContent" />
</ContentPage.Behaviors>
<Grid BackgroundColor="Red" Padding="0" Margin="0">
    <BlazorWebView HostPage="wwwroot/index.html" Margin="0">
        <BlazorWebView.RootComponents>
            <RootComponent Selector="#app" ComponentType="{x:Type local:Components.Routes}" />
        </BlazorWebView.RootComponents>
    </BlazorWebView>
</Grid>

</ContentPage>

enter image description here


Solution

  • I can reproduce the issue and the issue is caused by setting the status bar color either via iOS platform or using .NET MAUI toolkit, there is a gap between the Blazor WebView and the status bar. See [BUG] Blazor Hybrid white gap/field below status bar #19778

    To fix it, you can add the below code in your MainpPage.xaml.cs:

    using Microsoft.Maui.Platform;
    #if IOS
    
    using UIKit;
    
    #endif
    
    namespace MauiAppHybridApp
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            protected override void OnHandlerChanged()
            {
                base.OnHandlerChanged();
    #if IOS
    
                var window = this.GetParentWindow()?.Handler?.PlatformView as UIWindow;
    
                if (window is not null)
                {
                    var topPadding = window?.SafeAreaInsets.Top ?? 0;
                    var statusBar = new UIView(new CoreGraphics.CGRect(0, 0, UIScreen.MainScreen.Bounds.Size.Width, topPadding))
                    {
                        BackgroundColor = Colors.White.ToPlatform()
                    };
    
                    var view = this.Handler?.PlatformView as UIView;
                    if (view is not null)
                    {
                        view?.AddSubview(statusBar);
    
                    }
                }
    #endif
            }
        }
    }