Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part? Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part? wpf wpf

Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part?


The issue with using the DataTrigger/Binding solution mentioned above are two-fold. The first is you actually end up with a binding warning that you can't find the relative source for the selected item. The bigger issue however is that you've cluttered up your data templates and made them specific to a ComboBox.

The solution I present better follows WPF designs in that it uses a DataTemplateSelector on which you can specify separate templates using its SelectedItemTemplate and DropDownItemsTemplate properties as well as ‘selector’ variants for both.

Note: Updated for C#9 with nullability enabled and using pattern matching during the search

public class ComboBoxTemplateSelector : DataTemplateSelector {    public DataTemplate?         SelectedItemTemplate          { get; set; }    public DataTemplateSelector? SelectedItemTemplateSelector  { get; set; }    public DataTemplate?         DropdownItemsTemplate         { get; set; }    public DataTemplateSelector? DropdownItemsTemplateSelector { get; set; }    public override DataTemplate SelectTemplate(object item, DependencyObject container) {        var itemToCheck = container;        // Search up the visual tree, stopping at either a ComboBox or        // a ComboBoxItem (or null). This will determine which template to use        while(itemToCheck is not null        and not ComboBox        and not ComboBoxItem)            itemToCheck = VisualTreeHelper.GetParent(itemToCheck);        // If you stopped at a ComboBoxItem, you're in the dropdown        var inDropDown = itemToCheck is ComboBoxItem;        return inDropDown            ? DropdownItemsTemplate ?? DropdownItemsTemplateSelector?.SelectTemplate(item, container)            : SelectedItemTemplate  ?? SelectedItemTemplateSelector?.SelectTemplate(item, container);     }}

To make it easier to use in XAML, I've also included a markup extension that simply creates and returns the above class in its ProvideValue function.

public class ComboBoxTemplateSelectorExtension : MarkupExtension {    public DataTemplate?         SelectedItemTemplate          { get; set; }    public DataTemplateSelector? SelectedItemTemplateSelector  { get; set; }    public DataTemplate?         DropdownItemsTemplate         { get; set; }    public DataTemplateSelector? DropdownItemsTemplateSelector { get; set; }    public override object ProvideValue(IServiceProvider serviceProvider)        => new ComboBoxTemplateSelector(){            SelectedItemTemplate          = SelectedItemTemplate,            SelectedItemTemplateSelector  = SelectedItemTemplateSelector,            DropdownItemsTemplate         = DropdownItemsTemplate,            DropdownItemsTemplateSelector = DropdownItemsTemplateSelector        };}

And here's how you use it. Nice, clean and clear and your templates stay 'pure'

Note: 'is:' here is my xmlns mapping for where I put the class in code. Make sure to import your own namespace and change 'is:' as appropriate.

<ComboBox x:Name="MyComboBox"    ItemsSource="{Binding Items}"    ItemTemplateSelector="{is:ComboBoxTemplateSelector        SelectedItemTemplate={StaticResource MySelectedItemTemplate},        DropdownItemsTemplate={StaticResource MyDropDownItemTemplate}}" />

You can also use DataTemplateSelectors if you prefer...

<ComboBox x:Name="MyComboBox"    ItemsSource="{Binding Items}"    ItemTemplateSelector="{is:ComboBoxTemplateSelector        SelectedItemTemplateSelector={StaticResource MySelectedItemTemplateSelector},        DropdownItemsTemplateSelector={StaticResource MyDropDownItemTemplateSelector}}" />

Or mix and match! Here I'm using a template for the selected item, but a template selector for the DropDown items.

<ComboBox x:Name="MyComboBox"    ItemsSource="{Binding Items}"    ItemTemplateSelector="{is:ComboBoxTemplateSelector        SelectedItemTemplate={StaticResource MySelectedItemTemplate},        DropdownItemsTemplateSelector={StaticResource MyDropDownItemTemplateSelector}}" />

Additionally, if you don't specify a Template or a TemplateSelector for the selected or dropdown items, it simply falls back to the regular resolving of data templates based on data types, again, as you would expect. So, for instance, in the below case, the selected item has its template explicitly set, but the dropdown will inherit whichever data template applies for the DataType of the object in the data context.

<ComboBox x:Name="MyComboBox"    ItemsSource="{Binding Items}"    ItemTemplateSelector="{is:ComboBoxTemplateSelector        SelectedItemTemplate={StaticResource MyTemplate} />

Enjoy!


Simple solution:

<DataTemplate>    <StackPanel>        <TextBlock Text="{Binding Name}"/>        <TextBlock Text="{Binding Address}">            <TextBlock.Style>                <Style TargetType="TextBlock">                    <Style.Triggers>                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">                            <Setter Property="Visibility" Value="Collapsed"/>                        </DataTrigger>                    </Style.Triggers>                </Style>            </TextBlock.Style>        </TextBlock>    </StackPanel></DataTemplate>

(Note that the element that is selected and displayed in the box and not the list is not inside a ComboBoxItem hence the trigger on Null)

If you want to switch out the whole template you can do that as well by using the trigger to e.g. apply a different ContentTemplate to a ContentControl. This also allows you to retain a default DataType-based template selection if you just change the template for this selective case, e.g.:

<ComboBox.ItemTemplate>    <DataTemplate>        <ContentControl Content="{Binding}">            <ContentControl.Style>                <Style TargetType="ContentControl">                    <Style.Triggers>                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}"                                        Value="{x:Null}">                            <Setter Property="ContentTemplate">                                <Setter.Value>                                    <DataTemplate>                                        <!-- ... -->                                    </DataTemplate>                                </Setter.Value>                            </Setter>                        </DataTrigger>                    </Style.Triggers>                </Style>            </ContentControl.Style>        </ContentControl>    </DataTemplate></ComboBox.ItemTemplate>

Note that this method will cause binding errors as the relative source is not found for the selected item. For an alternate approach see MarqueIV's answer.


I was going to suggest using the combination of an ItemTemplate for the combo items, with the Text parameter as the title selection, but I see that ComboBox doesn't respect the Text parameter.

I dealt with something similar by overriding the ComboBox ControlTemplate. Here's the MSDN website with a sample for .NET 4.0.

In my solution, I change the ContentPresenter in the ComboBox template to have it bind to Text, with its ContentTemplate bound to a simple DataTemplate that contains a TextBlock like so:

<DataTemplate x:Uid="DataTemplate_1" x:Key="ComboSelectionBoxTemplate">    <TextBlock x:Uid="TextBlock_1" Text="{Binding}" /></DataTemplate>

with this in the ControlTemplate:

<ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding Text}" ContentTemplate="{StaticResource ComboSelectionBoxTemplate}" Margin="3,3,23,3" VerticalAlignment="Center" HorizontalAlignment="Left"/>

With this binding link, I am able to control the Combo selection display directly via the Text parameter on the control (which I bind to an appropriate value on my ViewModel).