Search code examples
c#wpfxamlcombobox

How to center align combobox selected item in WPF


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


Solution

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

    <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>