【问题标题】:Adding an object instance to a CompositeCollection as an item将对象实例作为项添加到 CompositeCollection
【发布时间】:2023-04-06 18:23:01
【问题描述】:

除了其他子集合之外,有没有办法将单个项目添加到 CompositeCollection(用作 ComboBox 的源)?

  • 项目的对象实例是 ViewModel 上的一个属性
  • 添加的项目和其他子集合中的项目都是 同一类型。

这是我所拥有的:

<ComboBox x:Name="combo">
    <ComboBox.Resources>
        <CollectionViewSource x:Key="CollectionAsAProperty" Source="{Binding CollectionA, Mode=TwoWay}" SelectedItem="{Binding CurrentItem}" />
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={x:Static local:MyViewModel.StaticCollection}}" />
            <CollectionContainer Collection="{Binding Source={StaticResource CollectionAsAProperty}}"/>

   ===> what should I add here to add another item of DataContext.AnotherItem

        </CompositeCollection>
    </ComboBox.ItemsSource>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

编辑:它与

有点合作
<ObjectDataProvider ObjectInstance="{x:Static local:MyViewModel.AnotherItem}"/>

但是,(1)它需要一个静态属性,并且(2)在附加的命令中(为简洁起见此处未显示),选择项的类型返回的是ObjectDataProvider,而不是MyViewModel.AnotherItem的类型,这会导致ViewModel有些痛苦

【问题讨论】:

  • 与其以这种方式解决此问题,您不认为将您的AnotherItem 包装在IEnumerable 中更容易,CollectionContainer 可以绑定到@987654328 @?这样,您提到的两个问题不再存在,因为您的属性不再必须是静态的,而且 DataType 将是正确的自定义类型 T。就 CompositeCollectionCollectionContainer 而言,您我给了他们一个新的List 当你实际上在那个列表中只有一项时(AnotherItem)=> 没有功能打嗝
  • @Viv,我这样做是为了让自己摆脱这个问题。

标签: wpf xaml binding compositecollection


【解决方案1】:

将复合集合移动到您的 viewModel 并在后面的代码中使用 Add method 添加所有不同的集合。

    var myAnimals = new List<Animal>() { new Animal() { Name = "Zebra" },
                                         new Animal() { Name = "Cobra" }} ;

    var myPeople = new List<Person>() { new Person() { Name = "Snake Pliskin" },
                                        new Person()  { Name = "OmegaMan" }};


    var FavoriteThings = new CompositeCollection();

    FavoriteThings.Add(myAnimals);
    FavoriteThings.Add(myPeople);

public class Animal
{
    public string Name { get; set; }
}


public class Person
{
    public string Name { get; set; }
}

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多