如何在 WPF 中居中对齐组合框所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28576488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:57:53  来源:igfitidea点击:

How to center align combobox selected item in WPF

c#wpfcombobox

提问by keerthee

I want combobox selected item alone center aligned while the drop down contents to be left aligned.

我希望组合框选定的项目单独居中对齐,而下拉内容左对齐。

To achieve this I made an entire copy of the default combobox and modified the Content Presenter of Toggle button horizontal alignment to Center

为了实现这一点,我制作了默认组合框的完整副本,并将切换按钮水平对齐的内容展示器修改为中心

Is there any simple approach to achieve this than to edit the entire template

有没有比编辑整个模板更简单的方法来实现这一点

采纳答案by keerthee

Assigning the HorizontalAlignment = "Center" in the ContentPresenter in ControlTemplate of the ComboBox

在 ComboBox 的 ControlTemplate 中的 ContentPresenter 中分配 Horizo​​ntalAlignment = "Center"

<ControlTemplate x:Key="ComboBoxControlTemplate1" TargetType="{x:Type ComboBox}">
        <Grid x:Name="MainGrid" SnapsToDevicePixels="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
            </Grid.ColumnDefinitions>                
           <Popup ...... />
           <ToggleButton ...../>
           <ContentPresenter ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}" HorizontalAlignment="Center" IsHitTestVisible="False" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Grid>
</ControlTemplate>

回答by noontz

A simple approach that worked for me :

一种对我有用的简单方法:

<Style TargetType="ComboBox">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>

回答by Jawahar

You just need a trigger associated to the style of ComboBoxItem.

您只需要一个与 ComboBoxItem 样式相关联的触发器。

    <Style TargetType="ComboBoxItem">
        <Style.Triggers>
            <Trigger Property="IsSelected"
                     Value="True">
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
            </Trigger>
        </Style.Triggers>
    </Style>