TLJ*_*TLJ 2 .net c# combobox dictionary winforms
我正在寻找一种将字典绑定到 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
Run Code Online (Sandbox Code Playgroud)
==更新==
目前我有一个解决方法是调用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);
}
Run Code Online (Sandbox Code Playgroud)