我正在寻找一种方法将字典绑定到ComboBox上,这样当我更新字典时,ComboBox会自动反映出更改并显示在UI中。目前我只能填充ComboBox,但是一旦我更新字典,就无法反映到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
==更新==
目前我有一个解决方法,通过调用 combo.DataSource = new BindingSource(menuItems, null);
来刷新我的用户界面。
combo.DataSource = new BindingSource(menuItems, null);
来刷新我的用户界面。但我仍然喜欢我的方法,因为使用字典可以轻松检查重复键,而无需调用 #contains。 - TLJKeyValuePair
,它们确实具有Key
和Value
属性。除此之外,回答非常好。+1 - IAmJersh