Wpf combobox with custom text itemtemplate

I have a ComboBox with a custom ItemTemplate .

 <ComboBox Height="20" Width="200" SelectedItem="{Binding Path=SelectedDesign}" ItemsSource="{Binding Path=Designs}" HorizontalAlignment="Left" ScrollViewer.CanContentScroll="False"> <ComboBox.ItemTemplate> <DataTemplate DataType="{x:Type formdesign:FormDesignContainer}"> <Rectangle Width="200" Height="100"> <Rectangle.Fill> <ImageBrush ImageSource="{Binding Path=ImageThumb}" Stretch="Uniform" /> </Rectangle.Fill> </Rectangle> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> 

It works well. However, WPF is trying to draw a rectangle as Combobox text. How can I set the "text" for this template. By "text" I mean a string or control that represents the selected item and is written to the combo box when the item is selected

In other words, I would like to do this:

enter image description here

But now I got it

enter image description here

+4
source share
3 answers

Try setting SelectionBoxItemTemplate with a TextBlock. It appears that SelectionBoxItemTemplate is read-only. So another approach is to override ItemContainerStyle.Template. Example

+1
source

I found this Ray Burns solution a good approach. You can define two DataTemplate one for the items in the drop-down list and the other for the selected item that should be displayed in Combobox . Using a trigger and checking the visual tree, he decides which one to use.

 <Window.Resources> <DataTemplate x:Key="NormalItemTemplate" ...> ... </DataTemplate> <DataTemplate x:Key="SelectionBoxTemplate" ...> ... </DataTemplate> <DataTemplate x:Key="CombinedTemplate"> <ContentPresenter x:Name="Presenter" Content="{Binding}" ContentTemplate="{StaticResource NormalItemTemplate}" /> <DataTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}" Value="{x:Null}"> <Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource SelectionBoxTemplate}" /> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> </Window.Resources> ... <ComboBox ItemTemplate="{StaticResource CombinedTemplate}" ItemsSource="..."/> 
0
source

Add a Textblock to the data file and link it or add Contentpersenter to the rectangle Edit: it seems that I did not get what you did to execute,

-1
source

All Articles