I have a generic style for a ListBox that overwrites the ItemTemplate to use RadioButtons. It works great, EXCEPT when I set a DisplayMemberPath. Then I just get the .ToString() of the item in the ListBox.
I feel like I’m missing something simple here… can someone help me spot it?
<Style x:Key="RadioButtonListBoxStyle" TargetType="{x:Type ListBox}">
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle" />
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="Margin" Value="2, 2, 2, 0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="Transparent">
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}" VerticalAlignment="Center"
IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
My ListBox is bound to a List<T> of KeyValuePairs. If I remove the Style, the DisplayMemberPath shows up correctly so it must be something with the style.
<ListBox Style="{StaticResource RadioButtonListBoxStyle}"
ItemsSource="{Binding MyCollection}"
DisplayMemberPath="Value" SelectedValuePath="Key" />
Why exactly do you want to keep
DisplayMemberPath? Its just a shortcut for anItemTemplatecontaining aTextBlockshowing the value inDisplayMemberPath. With your ownItemTemplateyou have much more flexibility what and how you want to display.Just add a
TextBlockinto yourItemTemplateand setText="{Binding Value}"and you have what you want.As described here:
DisplayMemberPathprovides a simple way to a template, but you want a different one. You can’t and you don’t need both.