Wpf ComboBox 选定项对齐

Wpf ComoBox Selected Item Alignment

您好,我在我的 wpf 应用程序中使用 Reuxables Free Theme Inc

我通过这种方式将主题添加到 App.xaml:

 <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/ReuxablesLegacy;component/inc.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

在我的 Main.xaml 中,我默认使用组合框,其内容左对齐:

我想将组合框的内容右对齐。

当我尝试时 HorizontalContentAlignment="Right" 没有任何改变。

我尝试了 TextBlock.TextAlignment="Right" 结果是这样的:

这次组合框项目向右对齐,但是在此图片中为“1”的所选项目仍然向左对齐。

无论我如何尝试,我都无法将所选项目右对齐。我做错了什么?

如果您查看 MSDN 上的 ComboBox Styles and Templates 页面,您会发现 WPF 中使用的 ComboBox 默认为 ControlTemplate。它太大而无法在此处显示,但是如果您向下看页面,您会看到一个名为 PART_EditableTextBoxTextBox 控件,如下所示:

  <TextBox x:Name="PART_EditableTextBox"
           Style="{x:Null}"
           Template="{StaticResource ComboBoxTextBox}"
           HorizontalAlignment="Left"
           VerticalAlignment="Bottom"
           Margin="3,3,23,3"
           Focusable="True"
           Background="Transparent"
           Visibility="Hidden"
           IsReadOnly="{TemplateBinding IsReadOnly}" />

这是用于所选值的控件,如您所见,它的 HorizontalAlignment 属性 被硬编码为 "Left",因此此 TextBox 中的文本将始终向左对齐。

因此,要将文本右对齐,您需要为 ComboBox 定义自己的 ControlTemplate。您可以在 MSDN 的 Control Authoring Overview 页面中找到如何执行此操作。基本上,您只需要复制默认的 ControlTemplate 并将上面的 TextBox 替换为下面的 TextBox

  <TextBox x:Name="PART_EditableTextBox"
           Style="{x:Null}"
           Template="{StaticResource ComboBoxTextBox}"
           HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
           VerticalAlignment="Bottom"
           Margin="3,3,23,3"
           Focusable="True"
           Background="Transparent"
           Visibility="Hidden"
           IsReadOnly="{TemplateBinding IsReadOnly}" />

完成此操作并将新 ControlTemplate 应用到 ComboBoxTemplate 属性 并设置 HorizontalContentAlignment 属性 到 Right,那么您最终应该会看到您选择的值文本右对齐。