MAUI怎么实现自定义导航栏 MAUI Shell TitleView用法

来源:这里教程网 时间:2026-02-21 17:34:03 作者:

MAUI 自定义导航栏的核心:Shell.TitleView

MAUI 中实现自定义导航栏,最标准、推荐的方式就是用 Shell.TitleView。它允许你完全替换默认的标题栏区域(包括标题文字、返回按钮等),用任意 XAML 内容(比如 StackLayout、Grid、Image、Button 等)来构建自己的导航栏外观和交互。

启用 TitleView 前要确认 Shell 结构

确保你的页面是 Shell 的子页面(即在 AppShell.xaml 中通过 FlyoutItem 或 TabBar 导航到该页),否则 TitleView 不生效。页面本身不需要继承 ShellContent,而是作为 ContentPage 放在 ShellContent.ContentTemplate 里。

AppShell.xaml 中类似:
<shellcontent contenttemplate="{DataTemplate local:MyPage}"></shellcontent>
MyPage.xaml 是普通 ContentPage,顶部加上
Shell.TitleView
即可生效

在页面中使用 TitleView 的基本写法

直接在 ContentPage 根元素内添加

Shell.TitleView
,里面放你想要的 UI:

<ContentPage ...>
  <Shell.TitleView>
    <Grid BackgroundColor="LightBlue" Padding="10">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
      </Grid.ColumnDefinitions>
      <Button Text="←" Command="{Binding GoBackCommand}" Grid.Column="0"/>
      <Label Text="我的页面" HorizontalOptions="Center" Grid.Column="1"/>
      <Button Text="⋯" Grid.Column="2"/>
    </Grid>
  </Shell.TitleView>
<p><!-- 页面主体内容 -->
<VerticalStackLayout Padding="20">
<Label Text="页面内容"/>
</VerticalStackLayout>
</ContentPage>

注意:

Shell.TitleView
必须是 ContentPage 的直接子元素,不能嵌套在其他布局里;它不会影响页面主体内容的布局位置,系统会自动为 TitleView 预留顶部空间。

常用技巧与注意事项

高度控制:TitleView 默认高度跟随平台(iOS 约 44,Android 约 56),如需固定高度,给外层容器加
HeightRequest
,但建议优先适配平台习惯
返回逻辑:系统返回按钮会被隐藏,需手动绑定命令或调用
Shell.GoToAsync("..")
实现返回
状态栏适配:iOS 上 TitleView 默认不覆盖状态栏;如需融合,设置
Shell.NavBarIsVisible="False"
并自行处理全屏导航栏(更复杂,非必需)
动态更新:TitleView 支持绑定,比如
<label text="{Binding PageTitle}"></label>
,配合 ViewModel 更新标题

基本上就这些。TitleView 灵活又轻量,不用重写 Shell 模板,适合大多数定制需求。如果需要更底层控制(比如全局统一导航栏样式或动画),才考虑自定义 ShellRenderer 或用 NavigationPage 替代 Shell —— 但那是另一条路了。

相关推荐