[英]How To Bind A Dictionary To A ComboBox In WinForms?
I am looking for a way to bind a Dictionary to a ComboBox 我正在寻找一种将字典绑定到ComboBox的方法
such that when I update dictionary the combobox, it will reflect the change automatically back to UI. 这样,当我更新字典组合框时,它将自动将更改反映回UI。
Now I can only populate combobox but once I update the dictionary nothing reflect to combobox. 现在,我只能填充组合框,但是一旦更新字典,任何内容都无法反映到组合框。
Dictionary<String,String> menuItems = new Dictionary<String,String>(){{"1","one"},{"2","two"}};
combo.DataSource = new BindingSource(menuItems, null);
combo.DisplayMember = "Value";
combo.ValueMember = "Key";
menuItems.Add("ok", "success"); // combobox doesn't get updated
==Update== == ==更新
Currently I have a workaround by calling combo.DataSource = new BindingSource(menuItems, null);
当前,我可以通过调用
combo.DataSource = new BindingSource(menuItems, null);
to refresh my UI. 刷新我的用户界面。
Dictionary
doesn't really have properties Key
and Value
. Dictionary
实际上没有属性Key
和Value
。 Use List<KeyValuePair<string,string>>
instead. 请改用
List<KeyValuePair<string,string>>
。 Also, you need to call ResetBindings()
for it to work. 另外,您需要调用
ResetBindings()
使其起作用。 See below: 见下文:
private void Form1_Load(object sender, EventArgs e)
{
//menuItems = new Dictionary<String, String>() { { "1", "one" }, { "2", "two" } };
menuItems = new List<KeyValuePair<string,string>>() { new KeyValuePair<string, string>("1","one"), new KeyValuePair<string, string>("2","two") };
bs = new BindingSource(menuItems, null);
comboBox1.DataSource = bs;
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
}
private void button1_Click(object sender, EventArgs e)
{
//menuItems.Add("3","three");
menuItems.Add(new KeyValuePair<string, string>("3", "three"));
bs.ResetBindings(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.