c# - 如何在 WinForms 中将字典绑定(bind)到组合框?

标签 c# .net winforms dictionary combobox

我正在寻找一种将字典绑定(bind)到组合框的方法

这样当我更新组合框的字典时,它会自动将更改反射(reflect)回 UI。

现在我只能填充组合框,但是一旦我更新了字典,组合框就没有任何反射(reflect)。

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); 来刷新我的 UI。

最佳答案

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

关于c# - 如何在 WinForms 中将字典绑定(bind)到组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748686/

相关文章:

c# - 通过 .NET COM 互操作调用方法时出错

c# - 如何创建用于访问 XNA 内容项目中文件的强类型结构?

c# - 什么是自托管?它可以与 web api 一起使用来与设备通信吗?

c# - 如何以编程方式滚动面板

c# - 更新动态生成的程序集

c# - 使用 FileHelpers 从 asp.net 文件上传读取 CSV 文件

c# - 如何编写一个桌面应用程序来读取/写入数据到连接到 PC 的 symbian 手机

c# - 给定一个整数数组。找到具有最大总和的最大子数组

c# - 带下拉菜单的 Windows.Forms 按钮

winforms - 建议触摸 Designer.cs 文件中的代码吗?