我正在寻找一种将字典绑定(bind)到组合框的方法
这样当我更新组合框的字典时,它会自动将更改反射(reflect)回 UI。
现在我只能填充组合框,但是一旦我更新了字典,组合框就没有任何反射(reflect)。
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。
最佳答案
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);
}
关于c# - 如何在 WinForms 中将字典绑定(bind)到组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748686/