WinUI 3:如何修复NavigationView底部项展开异常问题
当NavigationView底部项展开时,底部面板未自动适配高度导致内容遮挡,可通过以下两种方式修复:
方法一:自定义NavigationView模板调整布局
默认NavigationView的底部面板采用固定高度容器,展开时无法自动扩展。可修改ControlTemplate,将底部面板容器替换为自适应高度的布局控件:
- 提取NavigationView默认模板(在Blend中右键控件选择「编辑模板」→「编辑副本」生成)
- 找到名为
FooterPane的容器,移除固定高度约束,改为StackPanel实现自适应:
<!-- 替换原FooterPane布局 --> <StackPanel x:Name="FooterPane" Grid.Row="2" Orientation="Vertical"> <NavigationViewItemHeader x:Name="FooterHeader" Content="{TemplateBinding FooterHeader}" Visibility="Collapsed"/> <ItemsPresenter x:Name="FooterMenuItemsPresenter" ItemsSource="{TemplateBinding FooterMenuItems}"/> </StackPanel>
修改后底部面板会根据展开项的高度自动调整,避免内容被遮挡。
方法二:通过代码监听展开事件动态调整高度
若不想修改模板,可监听底部NavigationViewItem的展开/折叠事件,手动计算并设置面板高度:
// 页面加载时绑定事件 private void Page_Loaded(object sender, RoutedEventArgs e) { foreach (var item in NavView.FooterMenuItems) { if (item is NavigationViewItem navItem) { navItem.Expanded += FooterNavItem_Expanded; navItem.Collapsed += FooterNavItem_Collapsed; } } } private void FooterNavItem_Expanded(NavigationViewItem sender, object args) { UpdateFooterHeight(); } private void FooterNavItem_Collapsed(NavigationViewItem sender, object args) { UpdateFooterHeight(); } private void UpdateFooterHeight() { if (NavView.FindName("FooterPane") is FrameworkElement footerPane) { footerPane.Height = double.NaN; // 精确计算子项总高度 double totalHeight = 0; if (footerPane.Content is Panel panel) { foreach (FrameworkElement child in panel.Children) { totalHeight += child.ActualHeight; } footerPane.Height = totalHeight; } } }
注意:需确保底部面板初始高度设为Auto或double.NaN,避免固定高度限制。
内容的提问来源于stack exchange,提问作者Marek Pio
相关产品推荐
相关产品推荐

