2016-12-26 70 views
0

我有一個組合框,其中包含一個名稱列表:LastName + ", " + FirstName更改組合框中的一個項目的文本

當選擇一個名稱時,它將分別填充兩個文本框,分別爲名字和姓氏。

我想要做的是,如果名稱在文本框中更改,我希望將更改更新爲ComboBox,而無需重新加載整個事物。我的組合框不直接從數據庫中加載,所以我不能使用RefreshItem()

這是否可能?

+2

是的,它是。你如何填充你的組合框? – Fjut

+0

我使用我填充的ViewModel,然後將其設置爲DataSource。它包含int的索引和displaymember的字符串。我使用將不同來源的信息連接爲文本的規則來填充它,然後分配組合框的DisplayMember,ValueMember和DataSource –

+0

我相信這就是你要找的東西http://stackoverflow.com/questions/1064109/dynamically-改變項目中的項目在winforms組合框 – Fjut

回答

1

您可以實現INotifyPropertyChanged接口並使用BindingSource作爲ComboBox的DataContext。請參考下面的示例代碼。

Person.cs:

public class Person : INotifyPropertyChanged 
{ 
    private string _firstName; 
    public string FirstName 
    { 
     get { return _firstName; } 
     set { _firstName = value; NotifyPropertyChanged(); } 
    } 

    private string _lastName; 
    public string LastName 
    { 
     get { return _lastName; } 
     set { _lastName = value; NotifyPropertyChanged(); } 
    } 

    public string FullName { get { return LastName + ", " + FirstName; } } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

Form1.cs中:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     List<Person> people = new List<Person>() 
      { 
       new Person() { FirstName = "Donald", LastName = "Duck" }, 
       new Person() { FirstName = "Mickey", LastName = "Mouse" } 
      }; 
     BindingSource bs = new BindingSource(); 
     bs.DataSource = people; 
     comboBox1.DataSource = bs; 
     comboBox1.DisplayMember = "FullName"; 

     textBox1.DataBindings.Add(new Binding("Text", bs, "FirstName", false, DataSourceUpdateMode.OnPropertyChanged)); 
     textBox2.DataBindings.Add(new Binding("Text", bs, "LastName", false, DataSourceUpdateMode.OnPropertyChanged)); 

    } 
} 
相關問題