[英]Custom data binding on ComboBox
我正在尝试使用自定义ComboBoxItem类的多个实例填充ComboBox。 ComboBoxItem类如下所示:
class ComboBoxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
我可以填充CombBox
并读取它的值。 我唯一的问题是,当已有项目进入时,值应该绑定到我的ComboBox
。 但是我不知道如何告诉Binding
它应该使用ComboBoxItem.Value
作为Value字段。
//what to put in place of "SelectedItem"??
comboBox.DataBindings.Add(new Binding("SelectedItem", row, "F_KundenId", true, DataSourceUpdateMode.OnPropertyChanged));
这是我在应用程序中绑定所有Windows ComboBox的方式:
首先使用它来加载您的dataSource,在这种情况下为List:
public static void LoadComboBox(ComboBox comboBox, object dataSource, string valueMember, string displayMember)
{
comboBox.DataSource = dataSource;
comboBox.ValueMember = valueMember;
comboBox.DisplayMember = displayMember;
}
然后使用它将所选值绑定到“行”列“ F_KundenId”:
public static void BindComboBox(ComboBox comboBox, object boundDataSource, string boundDataMember)
{
comboBox.DataBindings.Clear();
comboBox.DataBindings.Add("SelectedValue", boundDataSource, boundDataMember);
}
这是一个可以在一次调用中同时完成这两项工作的辅助方法:
public static void LoadAndBindComboBox(ComboBox comboBox, object dataSource, string valueMember, string displayMember,
object boundDataSource, string boundDataMember)
{
LoadComboBox(comboBox, dataSource, valueMember, displayMember);
BindComboBox(comboBox, boundDataSource, boundDataMember);
}
此代码可与所需的任何数据源一起使用,并可绑定到DataTable,DataRow或对象的任何列。
例:
LoadAndBindComboBox(comboBox, myItems, "Value", "Text", row, "F_KundenId");
好吧,除了Mangist的答案,我想出了自己的解决方案。 无需任何自定义类。 只需使用Dictionary<Key, Value>
。 唯一的事情是,必须在运行时设置DisplayMember
和ValueMember
时小心。 如果重置ComboBox
的DataSource
(将其设置为null并重新绑定),则还需要设置两个Member属性。 然后只需使用BindingSource
对象将Dictionary<Key, Value>
绑定到ComboBox
。
private void InitCombos()
{
Dictionary<string, int> items = GetItems();
combo.DisplayMember = "Key";
combo.ValueMember = "Value";
combo.DataSource = new BindingSource(items, null);
}
//This was where my problem was. I didn't set the two Member properties of my ComboBox,
//thus preventing correct rebinding of DataSource
public void combo2_SelectedIndexChanged(object sender, EventArgs e)
{
combo.DataSource = null;
Dictionary<string, int> newItems = GetItems();
combo.DisplayMember = "Key";
combo.ValueMember = "Value";
combo.DataSource = new BindingSource(items, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.