gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:40:03 25 4
gpt4 key购买 nike

我正在寻找一种将字典绑定(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com