我有一些让我生气的 XAML 代码。首先为未引用的值添加一个虚拟项目。
为此我必须实现 CollectionViewSource
和一个 CompositeCollection
。
现在我无法选择第一个组合框项目,它出现了,但我无法选择它,因为我设置了 DisplayMemberPath
在 XAML 中(我猜是这样)。而且分隔符看起来也不如预期。
让我告诉你:
如果我不设置XAML DisplayMemberPath
,我可以使用虚拟元素,但绑定(bind)的元素显示不正确:
XAML:
<ComboBox x:Name="G_cb_content_zuordnung"
Margin="165,0,0,0"
Grid.Row="1"
SelectedIndex="0"
VerticalAlignment="Top"
DisplayMemberPath="PartnerID"
HorizontalAlignment="Left"
Width="119">
<ComboBox.Resources>
<CollectionViewSource x:Key="ComboCollection" Source="{Binding Path=mySelectedItem.Stammkinder}" />
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="Ohne Stammnummer" Name="NoPID" />
<Separator />
<CollectionContainer Collection="{Binding Source={StaticResource ComboCollection}, Mode=OneWay}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
我需要的只是一个虚拟/占位符组合框项目,该项目显示在 ObservableCollection<myClass>
的顶部。难道我的思维方式有问题吗?有更聪明的解决方案吗?我的解决方案中是否遗漏了某些内容?
最佳答案
使用第二种方法并显式为项目定义 DataTemplate
,而不是使用 DisplayMemberPath
属性:
<ComboBox xmlns:o="clr-namespace:APP.GLN_Organisator.Objects">
<ComboBox.Resources>
<CollectionViewSource x:Key="ComboCollection"
Source="{Binding Path=mySelectedItem.Stammkinder}" />
<!-- Define a DataTemplate here -->
<DataTemplate DataType="{x:Type o:ChildPartner}">
<TextBlock Text="{Binding PartnerID}"/>
</DataTemplate>
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="Ohne Stammnummer" Name="NoPID" />
<Separator />
<CollectionContainer Collection="{Binding Source={StaticResource ComboCollection}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
使用DataTemplate
,您可以告诉 WPF 您希望如何显示项目。如果您不提供任何 DataTemplate
并且不设置 DisplayMemberPath
属性值,WPF 将回退到简单的 ToString()
调用显示您的元素。这就是为什么您看到的是这些类型字符串而不是您的项目。
关于c# - 如何合并集合中的两个源并在组合框中正确显示它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50158262/