INotifyPropertyChangedインターフェイスを実装し、ComboBoxのDataContextとしてBindingSourceを使用できます。次のサンプルコードを参照してください。
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));
}
}
出典
2016-12-26 21:04:09
mm8
はい、そうです。あなたのコンボボックスはどのように埋め込みますか? – Fjut
私は、私が入力したViewModelを使用し、それをDataSourceとして設定します。これには、インデックスのintおよびdisplaymemberの文字列が含まれます。私は、さまざまなソースからの情報をテキストとして連結し、コンボボックスのDisplayMember、ValueMember、およびDataSourceを割り当てる規則を使用してデータを設定します。 –
これはあなたが探しているものだと思いますhttp://stackoverflow.com/questions/1064109/dynamically- – Fjut