绑定列表中对象的两个字段

时间:2013-10-03 18:07:59

标签: c# winforms data-binding

所以我有一个名为CustomerCollection

的班级
class CustomerCollection
    {
        public List<Customer> Customers { get; private set; }
...
}

列表中包含customers

class Customer
{
    public String ID { get; private set; }
    public String Name { get; private set; }

    public Customer(String id, String name)
    {
        ID = id;
        Name = name;
    }
}

是否可以绑定组合框和文本框,以便组合框显示CustomersCustomer Collection的所有可能ID,文本框将显示所选客户的名称?< / p>

编辑: 所以这就是我试过的

    private void InitializeCustomerCollection()
    {
        var customerCollection = new CustomerCollection();
        cmbx_custID.DataSource = customerCollection.Customers;
    }

但这不起作用并导致组合框被填充

X.Collections.Customer
X.Collections.Customer
X.Collections.Customer

2 个答案:

答案 0 :(得分:3)

这演示了如何使用您描述的行为向表单添加组合框。关键是设置ValueMember和DisplayMember。

  public partial class Form1 : Form
  {
     public Form1()
     {
        InitializeComponent();
        CustomerCollection cc = new CustomerCollection();
        cc.Customers.AddRange(new Customer[] {new Customer("1", "Adam"), new Customer("2", "Bob")});

        ComboBox ComboBox1 = new ComboBox()
           {Name = "ComboBox1", ValueMember = "ID", DisplayMember = "Name"};
        Controls.Add(ComboBox1);

        ComboBox1.DataSource = cc;
     }
  }

  public class Customer
  {
     public String ID { get; private set; }
     public String Name { get; private set; }

     public Customer(String id, String name)
     {
        ID = id;
        Name = name;
     }
  }

  class CustomerCollection : IListSource
  {
     public List<Customer> Customers { get; private set; }
     public CustomerCollection()
     {
        Customers = new List<Customer>();
     }

     public bool ContainsListCollection
     {
        get { return true; }
     }

     public System.Collections.IList GetList()
     {
        return Customers;
     }
  }

答案 1 :(得分:0)

在WPF中,您可以执行以下操作:

<ComboBox ItemSource={Binding Customers} x:Name="SelectedComboBox"/>
<TextBox Text={Binding SelectedItem.Name, ElementName=SelectedComboBox/>