StatusBarBehavior

StatusBarBehavior 提供自定义设备状态栏的颜色和样式的功能。

更新属性时,StatusBarBehavior 应用颜色和样式值。 这些值也基于 ApplyOn 属性应用,通过该属性可以定义使用哪个生命周期事件:

  • StatusBarApplyOn.OnBehaviorAttachedTo - 在行为已附加到页面时应用颜色和样式。 这是默认设置。
  • StatusBarApplyOn.OnPageNavigatedTo - 在已导航到页面时应用颜色和样式。

注意

如果应用程序按页面更改状态栏外观,则应使用 ApplyOn 属性的 StatusBarApplyOn.OnPageNavigatedTo 值。 否则,当返回时,系统将保留用户导航的起始页面而非目标页面的状态栏外观。

重要

.NET MAUI 社区工具包行为不会设置行为的 BindingContext,因为可以通过样式共享行为,并将其应用于多个控件。 有关详细信息,请参阅 .NET MAUI 行为

语法

XAML

包括 XAML 命名空间

若要在 XAML 中使用工具包,需要将以下 xmlns 添加到页面或视图中:

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"

因此,以下内容:

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

</ContentPage>

将被修改为包括 xmlns,如下所示:

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    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">

</ContentPage>

使用 StatusBarBehavior

StatusBarBehavior 可以在 XAML 中按如下所示方式使用:

<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"
             x:Class="MyLittleApp.MainPage">
    
    <ContentPage.Behaviors>
        <toolkit:StatusBarBehavior StatusBarColor="Fuchsia" StatusBarStyle="LightContent" />
    </ContentPage.Behaviors>

</ContentPage>

C#

StatusBarBehavior 可在 C# 中按如下所示方式使用:

class MyPage : ContentPage
{
    public MyPage()
    {
        this.Behaviors.Add(new StatusBarBehavior
        {
            StatusBarColor = Colors.Red,
            StatusBarStyle = StatusBarStyle.LightContent
        });
    }
}

可通过另一种方法访问 C# 的状态栏 API,可以直接调用这些方法,如以下代码片段所示:

class MyPage : ContentPage
{
    protected override void OnNavigatedTo(NavigatedToEventArgs args)
    {
        base.OnNavigatedTo(args);
        CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(statusBarColor);
        CommunityToolkit.Maui.Core.Platform.StatusBar.SetStyle(StatusBarStyle.LightContent);
    }
}

警告

如果要将此代码添加到 MainPage 的构造函数、OnAppearingOnNavigatedTo 方法中,请改用 Behavior。 直接在这些位置使用可能会使应用程序崩溃,因为特定于平台的组件可能未初始化。

配置

无需任何更改。

属性

属性 类型​​ 描述
ApplyOn StatusBarBehavior 何时应用状态栏颜色和样式。
StatusBarColor Color Microsoft.Maui.Graphics 命名空间中的 Color 名称。
StatusBarStyle StatusBarStyle 状态栏使用的样式,可以是 LightContent、DarkContent 或默认样式。

示例

可以在 .NET MAUI 社区工具包示例应用程序中查找此行为的示例。

API

可以在 .NET MAUI 社区工具包 GitHub 存储库查看StatusBarBehavior 的源代码