我正在寻找一种将Dictionary绑定到ComboBox的方法
这样当我更新字典组合框时,它会自动将更改反映回UI。
现在我只能填充组合框,但是一旦我更新字典,就没有任何反映到组合框。
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
==更新==
目前我通过调用combo.DataSource = new BindingSource(menuItems, null);
来刷新我的UI来解决方法。
答案 0 :(得分:4)
Dictionary
实际上没有属性Key
和Value
。请改用List<KeyValuePair<string,string>>
。此外,您需要致电ResetBindings()
才能使其正常运行。见下文:
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);
}