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

WinUI中如何让NavigationPage.TitleView内容居中?

解决WinUI中NavigationPage TitleView内容无法居中的问题

问题原因

WinUI里的NavigationPage.TitleView默认仅适配内部内容宽度,不会自动扩展至窗口全屏,导致子元素设置HorizontalOptions="Center"后,只能在自身内容宽度范围内居中,视觉上呈现左对齐效果。

解决方案

给TitleView的根布局同时设置HorizontalOptions="FillAndExpand"和HorizontalAlignment="Stretch",强制根布局占满导航栏的可用宽度,这样内部子元素就能基于全屏宽度实现居中。

修改后的代码:

<NavigationPage.TitleView>
    <Grid VerticalOptions="FillAndExpand" 
          BackgroundColor="CornflowerBlue"
          HorizontalOptions="FillAndExpand"
          HorizontalAlignment="Stretch">
        <Label Text="Center me!" 
               Style="{StaticResource H1}" 
               TextColor="White" 
               HorizontalOptions="Center"/>
    </Grid>
</NavigationPage.TitleView>

<ContentPage.Content>
    <Grid VerticalOptions="FillAndExpand" BackgroundColor="CornflowerBlue">
        <Label Text="Center me!" Style="{StaticResource H1}" TextColor="White" HorizontalOptions="Center"/>
    </Grid>
</ContentPage.Content>

补充说明

  • 若仍不生效,可检查是否存在自定义导航栏样式限制了宽度,需确保导航栏的Title容器允许拉伸
  • 无需手动设置WidthRequest,通过FillAndExpand搭配Stretch即可自适应窗口宽度,适配不同设备尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:19