2013-10-03 40 views
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; 
    } 
} 

名單有沒有去綁定組合框和文本使得組合框將在Customer Collection中顯示Customers的所有可能的ID,文本框將顯示所選客戶的名稱?

編輯: 所以這裏就是我試過

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

但是,這並不工作,導致組合框充滿

X.Collections.Customer 
X.Collections.Customer 
X.Collections.Customer 
+0

是的,這是可能的。你在使用什麼平臺? WPF?的WinForms? ASP.NET? – PoweredByOrange

+0

Winform。我忘了標記它。抱歉。 – Wusiji

+0

我不知道如何在WinForms中完成此操作。然而,你看到像你這樣的輸出的原因是因爲它不知道如何顯示你當前的對象。您或者需要爲其提供DisplayMemberPath(這是xaml/wpf中的內容),或者重載類.ToString()方法以使用您的客戶的名稱。 – gleng

回答

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; 
    } 
    } 
+0

像魅力一樣工作。謝謝! – Wusiji

0

在WPF中,你可以這樣做以下:

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