1

除了其他子集合之外,有没有办法将单个项目添加到 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 中造成一些痛苦

4

1 回答 1

0

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

    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; }
}
于 2013-10-27T15:19:32.087 回答