c#下拉列表的嵌套KeyValuePairs

本文关键字:KeyValuePairs 嵌套 下拉列表 | 更新日期: 2023-09-27 18:01:36

我在窗体上放置了一个下拉控件。今天,这个下拉菜单的数据源是KeyValuePair<'string','string'>,因此很容易直接将下拉菜单的'DisplayMember'属性分配给KeyValuePair的'Value'。

我的一个要求导致这个数据源被更改为KeyValuePair<'string', KeyValuePair<'string','string'>。这在我运行代码时给我带来了问题。这是因为'DisplayMember'被设置为'Value'导致下拉菜单项显示为('AB')(其中'A'和'B'是新数据源的KeyValuePair<'string','string'>中各自的字符串)。

我想分配'DisplayMember'属性下拉到'Key'在KeyValuePair<'string','string'>从改变的数据源。

旧要求-

KeyValuePair<'string','string'>('A','B')

下拉项显示- 'B'

新要求-

KeyValuePair<'string',KeyValuePair<'string','string'>('A', new KeyValuePair<'B','C'>)

下拉项应该显示- 'B'

是否有可能只在下拉菜单属性的变化实现?

已经检查了数据源,但它只显示了键值对的顶层,而不是层次模型。

c#下拉列表的嵌套KeyValuePairs

不幸的是,您不能使用DisplayMember绑定到嵌套属性。因此,试图将DisplayMember设置为"Value.Key"之类的东西是行不通的。但是,我建议创建一个自定义类型,将您的KeyValuePair<string, KeyValuePair<string, string>>>类型包装到一个对象中,并赋予它易于访问的属性。下面是一个例子:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        // This was the old way 
        //List<KeyValuePair<string, KeyValuePair<string, string>>> myList = new List<KeyValuePair<string, KeyValuePair<string, string>>>();
        //myList.Add(new KeyValuePair<string, KeyValuePair<string, string>>("A", new KeyValuePair<string, string>("B", "C")));
        //myList.Add(new KeyValuePair<string, KeyValuePair<string, string>>("D", new KeyValuePair<string, string>("E", "F")));
        //myList.Add(new KeyValuePair<string, KeyValuePair<string, string>>("G", new KeyValuePair<string, string>("H", "I")));
        // This is the new way
        List<CustomKeyValuePairWrapper> myList = new List<CustomKeyValuePairWrapper>();
        myList.Add(new CustomKeyValuePairWrapper("A", new KeyValuePair<string, string>("B", "C")));
        myList.Add(new CustomKeyValuePairWrapper("D", new KeyValuePair<string, string>("E", "F")));
        myList.Add(new CustomKeyValuePairWrapper("G", new KeyValuePair<string, string>("H", "I")));
        comboBox1.DataSource = myList;
        comboBox1.DisplayMember = "ValueKey";
    }
}
public class CustomKeyValuePairWrapper
{
    public string Key { get; private set; }
    public KeyValuePair<string, string> Value { get; private set; }
    public string ValueKey
    {
        get { return Value.Key; }
    }
    public CustomKeyValuePairWrapper(string key, KeyValuePair<string, string> value)
    {
        Key = key;
        Value = value;
    }
}

尝试如下:

public class CustomKeyValuePair
{
    public CustomKeyValuePair(string key, string value)
    {
        this.Key = key;
        this.Value = value;
    }
    public string Key { get; set; }
    public string Value { get; set; }
    public override string ToString()
    {
        return Key;
    }
}
KeyValuePair<'string',KeyValuePair<'string',CustomKeyValuePair>('A', new CustomKeyValuePair('B','C'))