首页 > 解决方案 > 除了最后一项之外,控件中的水平对齐似乎都被忽略了

问题描述

我有一个基于切换按钮的自定义单选按钮:

<Style TargetType="{x:Type local:ToolbarRadioButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
   <Setter Property="Width" Value="60"/>
   <Setter Property="Height" Value="60"/>
   <Setter Property="ContentTemplate">
       <Setter.Value>
           <DataTemplate>
               <StackPanel Orientation="Vertical">
                   <iconPacks:PackIconModern Kind="{Binding TbIcon, RelativeSource={RelativeSource AncestorType=RadioButton}}"
                                             Height="30" Width="35" HorizontalAlignment="Center"/>
                   <TextBlock Text="{Binding TbText, RelativeSource={RelativeSource AncestorType=RadioButton}}" FontSize="12"
                              HorizontalAlignment="Center"/>
               </StackPanel>
           </DataTemplate>
       </Setter.Value>
   </Setter>
</Style>

我使用这个控件来创建四个切换/单选按钮。我已经将数据模板中的项目水平居中,但我最终得到了这个:

在此处输入图像描述

预测及其图标似乎居中,但其他图标部分左对齐。他们都使用相同的控件,所以他们不应该都居中吗?

为清晰而编辑:无论我将它们放在哪个顺序中,预测始终是正确对齐的。文本中没有空格,图像中也没有空格,所有图像的大小都根据上面定义的控件进行调整。这是实现部分以防万一,尽管它们完全相同:

<StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="0">
    <customs:ToolbarRadioButton TbText="Day" TbIcon="CalendarDay" GroupName="calViewType" x:Name="dayOnOff"/>
    <customs:ToolbarRadioButton TbText="Week" TbIcon="CalendarWeek" GroupName="calViewType" x:Name="weekOnOff"/>
    <customs:ToolbarRadioButton TbText="Month" TbIcon="CalendarMonth" GroupName="calViewType" x:Name="monthOnOff" IsChecked="True"/>
    <customs:ToolbarRadioButton TbText="Forecast" TbIcon="PeopleMultiple" GroupName="calViewType" x:Name="forecastOnOff"/>
</StackPanel>

标签: c#wpfxamlcustom-controls

解决方案


对于未来的读者:我通过深入研究 Button 的文档找到了答案。按钮上有一个名为 Horizo​​ntalContentAlignment(当然是垂直)的属性,显然需要设置它来对齐视觉内容。您不能明确设置作为内容的项目的 Horizo​​ntalAlignment 属性;显然,按钮想为你做这件事。


推荐阅读