Search code examples
wpfcomboboxitemtemplate

How do i Style my ComboBox as well as its items in WPF?


I have a ComboBox which i want to style with some custom style. I was successful in providing the required style. In the style i have the following elements :

  • Template for a toggle button
  • A pop-up which holds items of the ComboBox

Almost all the links i referred to, used the same approach. But with this approach i am not able to provide a template for the items in the ComboBox. For some reason the item template i am defining is not being used for rendering the items. Could someone help me out? I am pasting a sample of code to make my problem statement clear(There might be mistakes in the code, i just want an idea to proceed).

 <Window.Resources>
    <Style x:Key="{x:Type ComboBox}" TargetType="{x:Type ComboBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <ToggleButton Template="{StaticResource MyToggleButton}"/>
                        <Popup >
                            <StackPanel>
                                <Border/>
                                <ItemsPresenter/>
                            </StackPanel>
                        </Popup>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <ComboBox Style="{StaticResource MyStyle}">
        <ComboBox.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</Grid>

Solution

  • If you're trying to provide a different ControlTemplate for your ComboBoxItem controls you need to set the ItemContainerStyle property on your ComboBox to a Style similar to what you've already done with the parent control, but for ComboBoxItem. ItemTemplate defines a DataTemplate to apply to the data for each item which is then injected into that ComboBoxItem ControlTemplate.

    <ComboBox Style="{StaticResource MyStyle}">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                            <Border>
                                <ContentPresenter/> <!--ItemTemplate is injected here-->
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=SomePropertyOnMyDataObject}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>