WinUI中AppBarButton的Icon未垂直居中问题求助
问题原因
AppBarButton的默认模板包含固定内边距和布局约束,当放置在高度仅32的自定义标题栏中时,内部图标会被挤压到底部,常规的VerticalContentAlignment设置无法覆盖模板内的布局规则。
方法1:调整内边距与对齐属性
直接移除AppBarButton的默认内边距,并强制设置垂直对齐,这是最简单的修复方式:
<AppBarButton Icon="Back" Height="32" IsEnabled="{x:Bind ContentFrame.CanGoBack}" VerticalAlignment="Center" Padding="0" LabelPosition="Collapsed"/>
方法2:自定义ControlTemplate
如果方法1无效,需要修改AppBarButton的默认模板,确保内部图标容器完全居中:
<AppBarButton Icon="Back" Height="32" IsEnabled="{x:Bind ContentFrame.CanGoBack}" LabelPosition="Collapsed"> <AppBarButton.Template> <ControlTemplate TargetType="AppBarButton"> <Grid x:Name="Root" Width="48" Height="{TemplateBinding Height}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="PointerOver"> <VisualState.Setters> <Setter Target="Root.Background" Value="{ThemeResource AppBarButtonBackgroundPointerOver}"/> <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource AppBarButtonForegroundPointerOver}"/> </VisualState.Setters> </VisualState> <VisualState x:Name="Pressed"> <VisualState.Setters> <Setter Target="Root.Background" Value="{ThemeResource AppBarButtonBackgroundPressed}"/> <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource AppBarButtonForegroundPressed}"/> </VisualState.Setters> </VisualState> <VisualState x:Name="Disabled"> <VisualState.Setters> <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource AppBarButtonForegroundDisabled}"/> </VisualState.Setters> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <VisualState.Setters> <Setter Target="Root.Background" Value="{ThemeResource AppBarButtonBackgroundFocused}"/> </VisualState.Setters> </VisualState> <VisualState x:Name="Unfocused"/> <VisualState x:Name="PointerFocused"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Icon}" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.AccessibilityView="Raw"/> </Grid> </ControlTemplate> </AppBarButton.Template> </AppBarButton>
方法3:替换为普通Button+FontIcon
若无需AppBarButton的特定样式,使用普通Button搭配FontIcon可以完全控制布局:
<Button Height="32" Width="32" IsEnabled="{x:Bind ContentFrame.CanGoBack}" Padding="0" Style="{StaticResource AccentButtonStyle}"> <!-- 可选:匹配AppBarButton样式 --> <FontIcon Glyph="" <!-- WinUI Back图标的Glyph编码 --> HorizontalAlignment="Center" VerticalAlignment="Center"/> </Button>
内容的提问来源于stack exchange,提问作者Error404
相关产品推荐
相关产品推荐

