简体   繁体   English

如何在 WinForms 中将字典绑定到列表框

[英]How to bind Dictionary to ListBox in WinForms

可以将字典绑定到列表框,在列表框和成员属性之间保持同步吗?

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 .) (无耻地摘自我自己的博客: 将 ComboBox 绑定到通用 Dictionary 。)

This means you can use SelectedValue to get hold of the corresponding dictionary key for the selected item in the ListBox.这意味着您可以使用 SelectedValue 来获取 ListBox 中所选项目的相应字典键。

        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();


        }

I think you can use events for that.我认为您可以为此使用事件。 Whenever something changes in ListBox, an eventHandler method will add/remove same thing from Dictionary.每当 ListBox 中的某些内容发生变化时,eventHandler 方法将从 Dictionary 中添加/删除相同的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM