C# 多个ItemsSource集合绑定

C# 多个ItemsSource集合绑定,c#,wpf,xaml,C#,Wpf,Xaml,如何将多个不同类型的集合绑定到ItemsControl的ItemsSource 使用单个绑定可以很好地工作: <ItemsControl ItemsSource="{Binding Foo}" /> 我建议将ListBox绑定到您在代码中构建的CompositeCollection。 在本例中,我使用的是ViewModel,但您也可以在代码隐藏中执行相同的操作。 您可以找到许多关于如何通过google为ViewModel实现ViewModelBase和DelegateCommand

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

使用单个绑定可以很好地工作:

<ItemsControl ItemsSource="{Binding Foo}" />

我建议将ListBox绑定到您在代码中构建的CompositeCollection。 在本例中,我使用的是ViewModel,但您也可以在代码隐藏中执行相同的操作。 您可以找到许多关于如何通过google为ViewModel实现ViewModelBase和DelegateCommand的示例

下面是此示例的细分:

  • 此示例将Customer和Person对象加载到两个ObservableCollection容器中,以支持修改集合
  • ListBox将其ItemsSource绑定到包含两个ObservableCollection的CompositeCollection(ObjectCollection)
  • ListBox还将其SelectedItem绑定到一个对象(SelectedObject)以支持两种基本类型
  • 该按钮将添加一个新人员,以显示您可以修改CompositeCollection
  • 为了完整性,我在末尾添加了客户和人员定义
以下是视图:

<Window x:Class="StackOverflow.Views.MainView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Main Window" Height="400" Width="800">
  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListBox Grid.Row="0" 
             SelectedItem="{Binding Path=SelectedObject}"
             ItemsSource="{Binding Path=ObjectCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding FirstName}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Grid.Row="1" Content="Add Person" Command="{Binding Path=AddPerson}"/>
  </Grid>
</Window>

以下是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<object>(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<Person> items = ccItems.Collection as ObservableCollection<Person>;
        if (items != null)
        {
          Person p = new Person("AAAA", "BBBB");
          items.Add(p);
        }
      }
    }

    private bool CanAddPerson(object obj)
    {
      return true;
    }
  }
}
使用System.Collections.Generic;
使用System.Windows.Data;
使用System.Windows.Input;
使用ContextMenuNotFiring.Commands;
使用ContextMenuNotFiling.Models;
命名空间StackOverflow.ViewModels
{
公共类MainViewModel:ViewModelBase
{
公共主视图模型()
{
AddPerson=新的DelegateCommand(OnAddPerson、CanAddPerson);
CollectionContainer客户=新的CollectionContainer();
customers.Collection=Customer.GetSampleCustomerList();
CollectionContainer persons=新的CollectionContainer();
persons.Collection=Person.GetSamplePersonList();
_oc.Add(客户);
_oc.新增(人);
}
私有CompositeCollection _oc=新的CompositeCollection();
公共CompositeCollection对象集合
{
获取{return}
}
私有对象_so=null;
公共对象选择对象
{
获取{return\u so;}
设置
{
_so=价值;
}
}
公共ICommand AddPerson{get;set;}
个人(对象对象obj)
{
CollectionContainer ccItems=_oc[1]作为CollectionContainer;
如果(ccItems!=null)
{
ObservableCollection items=作为ObservableCollection的ccItems.Collection;
如果(项!=null)
{
人员p=新人员(“AAAA”、“BBBB”);
增加(p);
}
}
}
私人bool CanAddPerson(对象obj)
{
返回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<Customer> GetSampleCustomerList()
  {
    return new ObservableCollection<Customer>(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<Person> GetSamplePersonList()
  {
    return new ObservableCollection<Person>(new Person[4] {
            new Person("Bob", "Smith"), 
            new Person("Barry", "Jones"),
            new Person("Belinda", "Red"),
            new Person("Benny", "Hope")
        });
  }
}
公共类客户
{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公共客户(字符串firstName、字符串lastName)
{
this.FirstName=FirstName;
this.LastName=LastName;
}
公共静态ObservableCollection GetSampleCustomerList()
{
返回新的ObservableCollection(新客户[4]{
新客户(“查理”,“零”),
新客户(“Cathrine”、“One”),
新客户(“糖果”、“两个”),
新客户(“卡米”、“三”)
});
}
}
公共阶层人士
{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公众人物(字符串名、字符串名)
{
this.FirstName=FirstName;
this.LastName=LastName;
}
公共静态ObservableCollection GetSamplePersonList()
{
返回新的ObservableCollection(新人员[4]{
新人(“鲍勃”、“史密斯”),
新人(“巴里”、“琼斯”),
新人(“贝琳达”、“红色”),
新人(“本尼”、“希望”)
});
}
}

我认为这是最好的答案:


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

在代码隐藏/VM中构建CompositeCollection,而不是在XAML中将CollectionContainer绑定到VM的各个属性,这样做有什么好处?
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<Customer> GetSampleCustomerList()
  {
    return new ObservableCollection<Customer>(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<Person> GetSamplePersonList()
  {
    return new ObservableCollection<Person>(new Person[4] {
            new Person("Bob", "Smith"), 
            new Person("Barry", "Jones"),
            new Person("Belinda", "Red"),
            new Person("Benny", "Hope")
        });
  }
}