多个ItemsSource集合绑定

如何将不同类型的多个集合绑定到ItemsControl的ItemsSource?

使用单个绑定工作正常:

 

但是当我尝试使用CompositeCollection时,不会显示Foo中的项目:

         

我建议将ListBox绑定到您在代码中构建的CompositeCollection。 在这个例子中,我使用的是ViewModel,但你也可以在代码隐藏中做同样的事情。 您可以找到许多关于如何通过谷歌为ViewModel实现ViewModelBase和DelegateCommand的示例。

以下是此示例的细分:

  • 此示例将Customer和Person对象加载到两个ObservableCollection容器中,以支持修改集合。
  • ListBox将其ItemsSource绑定到CompositeCollection(ObjectCollection),后者包含两个ObservableCollections。
  • ListBox还将其SelectedItem绑定到一个对象(SelectedObject)以支持两种基类型。
  • Button添加了一个新Person,表明您可以修改CompositeCollection。
  • 为了完整性,我在最后添加了客户和人员定义。

这是视图:

                 

这是ViewModel:

 using System.Collections.Generic; using System.Windows.Data; using System.Windows.Input; using ContextMenuNotFiring.Commands; using ContextMenuNotFiring.Models; namespace StackOverflow.ViewModels { public class MainViewModel : ViewModelBase { public MainViewModel() { AddPerson = new DelegateCommand(OnAddPerson, CanAddPerson); CollectionContainer customers = new CollectionContainer(); customers.Collection = Customer.GetSampleCustomerList(); CollectionContainer persons = new CollectionContainer(); persons.Collection = Person.GetSamplePersonList(); _oc.Add(customers); _oc.Add(persons); } private CompositeCollection _oc = new CompositeCollection(); public CompositeCollection ObjectCollection { get { return _oc; } } private object _so = null; public object SelectedObject { get { return _so; } set { _so = value; } } public ICommand AddPerson { get; set; } private void OnAddPerson(object obj) { CollectionContainer ccItems = _oc[1] as CollectionContainer; if ( ccItems != null ) { ObservableCollection items = ccItems.Collection as ObservableCollection; if (items != null) { Person p = new Person("AAAA", "BBBB"); items.Add(p); } } } private bool CanAddPerson(object obj) { return true; } } } 

以下是模型:

 public class Customer { public String FirstName { get; set; } public String LastName { get; set; } public Customer(String firstName, String lastName) { this.FirstName = firstName; this.LastName = lastName; } public static ObservableCollection GetSampleCustomerList() { return new ObservableCollection(new Customer[4] { new Customer("Charlie", "Zero"), new Customer("Cathrine", "One"), new Customer("Candy", "Two"), new Customer("Cammy", "Three") }); } } public class Person { public String FirstName { get; set; } public String LastName { get; set; } public Person(String firstName, String lastName) { this.FirstName = firstName; this.LastName = lastName; } public static ObservableCollection GetSamplePersonList() { return new ObservableCollection(new Person[4] { new Person("Bob", "Smith"), new Person("Barry", "Jones"), new Person("Belinda", "Red"), new Person("Benny", "Hope") }); } } 

我相信这里的答案最好: 如何将CollectionContainer绑定到视图模型中的集合?

归结为CollectionContainer没有DataContext 。 您必须设置源,以便它可以找到DataContext并完成绑定。