How can I overwrite my ListBox's ItemTemplate and still keep the DisplayMemberPath?
Why exactly do you want to keep DisplayMemberPath
? Its just a shortcut for an ItemTemplate
containing a TextBlock
showing the value in DisplayMemberPath
. With your own ItemTemplate
you have much more flexibility what and how you want to display.
Just add a TextBlock
into your ItemTemplate
and set Text="{Binding Value}"
and you have what you want.
As described here:
This property is a simple way to define a default template that describes how to display the data objects.
DisplayMemberPath
provides a simple way to a template, but you want a different one. You can't and you don't need both.
I still can't figure out how to get it to draw using the DisplayMemberPath
, however I did find the piece I was missing to get it drawing using the ItemTemplate
- I needed the ContentTemplate
binding
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
ContentTemplate="{TemplateBinding ContentPresenter.ContentTemplate}"
IsChecked="{Binding Path=IsSelected,RelativeSource={
RelativeSource TemplatedParent},Mode=TwoWay}" />
Then in my XAML I can write:
<ListBox Style="{StaticResource RadioButtonListBoxStyle}"
ItemsSource="{Binding MyCollection}"
SelectedValuePath="Key">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks to dowhilefor for pointing out that DisplayMemberPath
is simply a shortcut way of writing the ItemTemplate
, and that both cannot be set at once.
I have been researching this same problem since morning and this thread helped me a lot. I investigated the solution and found out there is a way to support DisplayMemberPath even after defining a custom ListboxItem controltemplate in a style . The key is adding
ContentTemplateSelector="{TemplateBinding ContentControl.ContentTemplateSelector}"
to the contentpresenter( the radiobutton in case of this thread).
The reason this will work is because internally the displaymemberpath property causes the Listbox to assign the ContentTemplateSelector to a "DisplayMemberTemplateSelector" template selector. Without this TemplateBinding in place, this selector does not take effect.
Cheers!