如何在WinForms中将字典绑定到ComboBox?

4
我正在寻找一种方法将字典绑定到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); 来刷新我的用户界面。

1个回答

7

Dictionary 实际上没有 KeyValue 属性。应该使用 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);
    }

enter image description here


你的解决方案非常接近我的解决方法。我一直在调用 combo.DataSource = new BindingSource(menuItems, null); 来刷新我的用户界面。但我仍然喜欢我的方法,因为使用字典可以轻松检查重复键,而无需调用 #contains。 - TLJ
1
这里说“谢谢”的方式是给一个回答点赞...:O) - jsanalytics
它所访问的属性位于集合中每个项目上,因此是 KeyValuePair,它们确实具有 KeyValue 属性。除此之外,回答非常好。+1 - IAmJersh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接