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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1506987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:15:15  来源:igfitidea点击:

How to bind Dictionary to ListBox in WinForms

c#winformsdictionarydata-bindinglistbox

提问by ???

It is possible to bind a Dictionary to a Listbox, keeping in sync between the Listbox and the member property?

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

采纳答案by Matt Hamilton

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 中所选项目的相应字典键。

回答by Tarik

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 中添加/删除相同的内容。

回答by WINSH WINSH

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


        }