It is possible to bind a dictionary to a listbox, keeping in sync between the listbox and the member property?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
var choices = new Dictionary<string, string>();
choices["A"] = "Arthur";
choices["F"] = "Ford";
choices["T"] = "Trillian";
choices["Z"] = "Zaphod";
listBox1.DataSource = new BindingSource(choices, null);
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
(Shamelessly lifted from my own blog: Bind a ComboBox to a generic Dictionary.)
This means you can use SelectedValue to get hold of the corresponding dictionary key for the selected item in the ListBox.
回答2:
I think you can use events for that. Whenever something changes in ListBox, an eventHandler method will add/remove same thing from Dictionary.
回答3:
label1.Text= listBox1.SelectedIndex.ToString();
if ( listBox1.SelectedItem is KeyValuePair<int,DockStyle>)
{
var temp1 = (KeyValuePair<int, DockStyle>)listBox1.SelectedItem;
label3.Text = temp1.Key.ToString();
label4.Text = temp1.Value.ToString();
}