1

所以我有一堂课叫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;
    }
}

是否可以绑定一个组合框和一个文本框,以便组合框将显示 in 的所有可能 id,CustomersCustomer Collection文本框将显示所选客户的姓名?

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

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

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

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

2 回答 2

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;
     }
  }
于 2013-10-03T18:30:43.503 回答
0

In WPF you can do something like the following:

<ComboBox ItemSource={Binding Customers} x:Name="SelectedComboBox"/>
<TextBox Text={Binding SelectedItem.Name, ElementName=SelectedComboBox/>
于 2013-10-03T18:11:39.060 回答