如何合并Collection中的两个源并在组合框中显示它们是正确的?

时间:2018-05-03 15:03:51

标签: c# wpf mvvm data-binding compositecollection

我有一些让我生气的XAML代码。它首先为未引用的值添加一个虚拟项目。

为此,我必须实施CollectionViewSourceCompositeCollection。 现在我无法选择第一个Combobox项目,它出现但我无法选择它,因为我在XAML中设置了DisplayMemberPath(我猜是这样)。分隔符看起来也不像预期的那样。

让我告诉你:

screenshot

如果我没有设置XAML DisplayMemberPath,我可以使用虚拟物品,但绑定的物品显示不正确:

screenshot

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>之上。我的思维方式错了吗?有更聪明的解决方案吗?我在解决方案中是否遗漏了什么?

1 个答案:

答案 0 :(得分:2)

使用您的第二种方法,明确为项目定义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()调用。这就是为什么你看到这些类型字符串而不是你的项目的原因。