Rac*_*hel 10 wpf xaml templates listbox
我有一个通用的样式ListBox覆盖ItemTemplate使用RadioButtons.它工作得很好,除了我设置时DisplayMemberPath.然后我就得到了.ToString()该项目的内容ListBox.
我觉得我在这里缺少一些简单的东西......有人可以帮助我发现它吗?
<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绑定到List<T>的KeyValuePairs.如果我删除了样式,则DisplayMemberPath显示正确,因此它必须是样式的东西.
<ListBox Style="{StaticResource RadioButtonListBoxStyle}"
         ItemsSource="{Binding MyCollection}"
         DisplayMemberPath="Value" SelectedValuePath="Key" />
为什么要保留DisplayMemberPath?它只是包含TextBlock的ItemTemplate的快捷方式,显示DisplayMemberPath中的值.使用您自己的ItemTemplate,您可以更灵活地显示您想要显示的内容和方式.只需将TextBlock添加到ItemTemplate中并设置即可Text="{Binding Value}".
如上所述这里
此属性是定义描述如何显示数据对象的默认模板的简单方法.
DisplayMemberPath为模板提供了一种简单的方法,但您需要一个不同的方法.你不能,你不需要两者.
我仍然不知道如何使用 来绘制它DisplayMemberPath,但是我确实找到了使用 来绘制它所缺少的部分ItemTemplate- 我需要ContentTemplate绑定
<RadioButton 
    Content="{TemplateBinding ContentPresenter.Content}" 
    ContentTemplate="{TemplateBinding ContentPresenter.ContentTemplate}"
    IsChecked="{Binding Path=IsSelected,RelativeSource={
                        RelativeSource TemplatedParent},Mode=TwoWay}" />
然后在我的 XAML 中我可以编写:
<ListBox Style="{StaticResource RadioButtonListBoxStyle}"
         ItemsSource="{Binding MyCollection}"
         SelectedValuePath="Key">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
感谢 dowhilefor 指出这DisplayMemberPath只是编写 , 的快捷方式ItemTemplate,并且两者不能同时设置。
| 归档时间: | 
 | 
| 查看次数: | 4287 次 | 
| 最近记录: |