c# - 如何合并集合中的两个源并在组合框中正确显示它们?

标签 c# wpf mvvm data-binding compositecollection

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

为此我必须实现 CollectionViewSource和一个 CompositeCollection 。 现在我无法选择第一个组合框项目,它出现了,但我无法选择它,因为我设置了 DisplayMemberPath在 XAML 中(我猜是这样)。而且分隔符看起来也不如预期。

让我告诉你:


screenshot


如果我不设置XAML DisplayMemberPath ,我可以使用虚拟元素,但绑定(bind)的元素显示不正确:

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> 的顶部。难道我的思维方式有问题吗?有更聪明的解决方案吗?我的解决方案中是否遗漏了某些内容?

最佳答案

使用第二种方法并显式为项目定义 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/

相关文章:

c# - WPF 中是否有等效的 MessageBox?

c# - 具有泛型和继承的编码风格

c# - 为什么 ItemsSource 没有在 DataGrid 中更新

c# - XAML 中的 WPF StringFormat 和本地化

data-binding - zkoss MVVM 更改为模型强制网格重新加载

c# - 我可以在 Mouse.Capture() 处于事件状态时获得 MouseLeave 事件吗?

c# - 释放 Assembly.LoadFrom 文件句柄

wpf - 当其他列的内容折叠时,网格列不填充剩余空间

C# WPF 矩形填充绑定(bind)

wpf - WPF 中的自定义向导控件添加和删除用户控件?