C# – WPF combobox selected item

ccomboboxselecteditemwpf

I have a combobox with few items displayed as image and text (placed side by side for each item). Now when i select an item from the combobox list i want to display something else (instead of same image and text) maybe another text or another image on the Combobox selecteditem area.

Is there a way i can achieve it.

Best Answer

The easiest way is to add an IsSelected Trigger to the DataTemplate(Itemstemplate) of the Combobox, I think you have two groups of Visual elements one for the regular data display and another for the selected visuals, When IsSelected property set on the ComboboxItem you need to Make the regular visuals hide and the other one show. The real trick here is to find the immediate ComboBoxItem user selected using FindAncestor .

<DataTemplate x:Key="yourDataTemplate">
 <Grid x:Name="regularVisuals" > ... </Grid>
 <Grid x:Name="selectedVisuals" Visibility="Collapsed"> ... </Grid>
<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ComboBoxItem}},Path=IsSelected}" Value="True">
        <Setter TargetName="regularVisuals" Property="Visibility" Value="Visible"/>
        <Setter TargetName="selectedVisuals" Property="Visibility" Value="Collapsed"/>
    </DataTrigger>
</DataTemplate.Triggers>