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

.NET MAUI 如何在TitleBar中放置按钮?

在.NET MAUI自定义标题栏添加指定位置按钮

要在自动生成的标题栏(由NavigationPage提供)里指定位置放置按钮,最直接的方式是使用MAUI官方提供的TitleView属性,它允许你完全自定义标题栏的内容,具体实现步骤如下:

  • 确保页面嵌套在NavigationPage中
    默认标题栏由NavigationPage提供,需先确保你的页面是NavigationPage的子页面。若未设置,可在App.xaml.cs中初始化导航结构:

    MainPage = new NavigationPage(new YourTargetPage());
    
  • 在ContentPage中定义TitleView
    直接在ContentPage的XAML里添加TitleView,通过布局容器(如HorizontalStackLayout)精准控制元素位置。比如将标题文本居中、按钮放在右侧(匹配你参考的布局位置):

    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="YourAppNamespace.YourTargetPage">
    
        <ContentPage.TitleView>
            <HorizontalStackLayout HorizontalOptions="FillAndExpand" VerticalOptions="Center">
                <!-- 居中显示的标题文本 -->
                <Label Text="你的页面标题" 
                       HorizontalOptions="Center"
                       FontSize="Title"
                       FontAttributes="Bold"/>
                <!-- 右侧的操作按钮 -->
                <Button Text="操作" 
                        HorizontalOptions="End"
                        Padding="10,5"
                        Clicked="OnActionButtonClicked"/>
            </HorizontalStackLayout>
        </ContentPage.TitleView>
    
        <!-- 页面主体内容 -->
        <StackLayout>
            <!-- 这里添加页面的其他控件 -->
        </StackLayout>
    </ContentPage>
    
  • 后台处理按钮点击事件
    在对应的.cs文件中添加按钮点击的逻辑:

    private void OnActionButtonClicked(object sender, EventArgs e)
    {
        // 编写按钮点击后的操作,比如弹出提示、页面导航等
        DisplayAlert("提示", "按钮已触发", "确定");
    }
    
  • 适配不同平台样式(可选)
    若需针对iOS、Android、Windows等平台微调标题栏高度或样式,可通过平台特定值设置:

    <ContentPage.Resources>
        <Style TargetType="HorizontalStackLayout">
            <Setter Property="HeightRequest" 
                    Value="{OnPlatform iOS=44, Android=56, Windows=48}"/>
        </Style>
    </ContentPage.Resources>
    

这种方式既保留了导航栏的原生交互(如返回按钮),又能完全自定义标题栏内元素的位置和样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:20:26