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
相关产品推荐
相关产品推荐

