所以我有一个名为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;
}
}
是否可以绑定组合框和文本框,以便组合框显示Customers
中Customer Collection
的所有可能ID,文本框将显示所选客户的名称?< / p>
编辑: 所以这就是我试过的
private void InitializeCustomerCollection()
{
var customerCollection = new CustomerCollection();
cmbx_custID.DataSource = customerCollection.Customers;
}
但这不起作用并导致组合框被填充
X.Collections.Customer
X.Collections.Customer
X.Collections.Customer
答案 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/>