问题描述
我具有ListBox
的通用样式,该样式会覆盖ItemTemplate
以使用RadioButtons
.很好,除了我设置DisplayMemberPath
时.然后,我只需在ListBox
中获得该项目的.ToString()
.
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>
我的ListBox
绑定到KeyValuePairs
的List<T>
.如果我删除了样式,则DisplayMemberPath
会正确显示,因此它必须与样式有关.
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" />
推荐答案
为什么要保留DisplayMemberPath
?它只是包含TextBlock
的ItemTemplate
的快捷方式,其中显示DisplayMemberPath
中的值.有了自己的ItemTemplate
,您可以更加灵活地显示内容和显示方式.
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.
只需在ItemTemplate
中添加一个TextBlock
并设置Text="{Binding Value}"
,您便拥有了想要的东西.
Just add a TextBlock
into your ItemTemplate
and set Text="{Binding Value}"
and you have what you want.
如此处 :
DisplayMemberPath
为模板提供了一种简单的方法,但是您想要一个不同的模板.您可以,也不需要.
DisplayMemberPath
provides a simple way to a template, but you want a different one. You can't and you don't need both.
这篇关于如何覆盖列表框的ItemTemplate并仍然保留DisplayMemberPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!