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

WinUI3:为何不同模板创建的NavigationView顶部显示有差异?

WinUI3中NavigationView顶部显示差异的原因分析

在WinUI3 Gallery或通过Template Studio创建的应用中,NavigationView默认外观的顶部存在空白区域;但使用Visual Studio默认模板创建的应用中,NavigationView的顶部显示样式却存在差异,且该差异并非由ViewModel因素控制。

代码示例

Template Studio/WinUI3 Gallery中的代码

<!--在Template Studio或WinUI3 Gallery中-->
<Page>
    <Grid>
        <NavigationView PaneDisplayMode="LeftCompact"/>
    </Grid>
</Page>

Visual Studio默认模板中的代码

<!--在我使用Visual Studio默认模板创建的应用中-->
<Page>
    <Grid>
        <NavigationView PaneDisplayMode="LeftCompact"/>
    </Grid>
</Page>

显示效果差异

  • Template Studio/WinUI3 Gallery:NavigationView顶部存在明显空白,导航栏与窗口顶部有间距
  • Visual Studio默认模板:NavigationView顶部紧贴窗口顶部,无额外空白

补充验证

即使简化Template Studio创建的应用的ShellPage代码(如下),外观差异依然存在:

C#代码

public sealed partial class ShellPage : Page
{
    public ShellPage()
    {
        InitializeComponent();
    }
}

XAML代码

<Page
    x:Class="TemplateStudioApp.Views.ShellPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    
    <NavigationView PaneDisplayMode="LeftCompact"/>
</Page>

差异原因分析

1. 自定义标题栏配置

Template Studio和WinUI3 Gallery默认启用了自定义标题栏,通常会通过Window.ExtendsContentIntoTitleBar = true或CoreApplication.GetCurrentView().TitleBar相关配置,将窗口标题栏的空间预留出来,导致NavigationView顶部出现空白。而Visual Studio默认模板未配置自定义标题栏,NavigationView会自动填充窗口顶部区域。

2. Page的默认Padding设置

部分模板会在应用的资源字典或Page的默认样式中,给根元素设置TopPadding来适配自定义标题栏的高度。即使删除ViewModel,这些样式设置依然存在,导致NavigationView上方出现空白。

3. NavigationView的自动标题栏填充属性

NavigationView有一个IsTitleBarAutoPaddingEnabled属性,默认在自定义标题栏场景下会自动启用,给顶部添加padding以避开标题栏区域。这也是导致顶部空白的关键因素之一,可通过显式设置该属性为False验证:

<NavigationView PaneDisplayMode="LeftCompact" IsTitleBarAutoPaddingEnabled="False"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:30:46