2016-12-26 29 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)); 

    } 
} 
相关问题