C#:如何从类方法绑定到 ListBox DisplayMember 和 ValueMember 结果?

And*_*ran 0 c# listbox function valuemember

我正在尝试创建 ListBox,其中我将拥有键值对。我从课堂上获得的那些数据是从 getter 那里获得的。

班级:

public class myClass
{
    private int key;
    private string value;

    public myClass() { }

    public int GetKey()
    {
        return this.key;
    }

    public int GetValue()
    {
        return this.value;
    }
}
Run Code Online (Sandbox Code Playgroud)

程序:

private List<myClass> myList;

public void Something()
{
    myList = new myList<myClass>();

    // code for fill myList

    this.myListBox.DataSource = myList;
    this.myListBox.DisplayMember = ??; // wanted something like myList.Items.GetValue()
    this.myListBox.ValueMember = ??; // wanted something like myList.Items.GetKey()
    this.myListBox.DataBind();
}
Run Code Online (Sandbox Code Playgroud)

它类似于本主题 [ Cannot do key-value in listbox in C# ] 但我需要使用从方法返回值的类。

是否可以做一些简单的事情,或者我最好完全重新设计我的思维流程(和这个解决方案)?

谢谢你的建议!

Ste*_*eve 5

DisplayMemberValueMember特性要求中使用的属性的名称(字符串)。你不能使用一种方法。所以你有两个选择。更改您的类以返回属性或创建一个从 myClass 派生的类,您可以在其中添加两个缺少的属性

public class myClass2 : myClass
{

    public myClass2() { }

    public int MyKey
    {
        get{ return base.GetKey();}
        set{ base.SetKey(value);}
    }

    public string MyValue
    {
        get{return base.GetValue();}
        set{base.SetValue(value);}
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您已经进行了这些更改,您可以使用新类更改您的列表(但修复初始化)

// Here you declare a list of myClass elements
private List<myClass2> myList;

public void Something()
{
    // Here you initialize a list of myClass elements
    myList = new List<myClass2>();

    // code for fill myList
    myList.Add(new myClass2() {MyKey = 1, MyValue = "Test"});

    myListBox.DataSource = myList;
    myListBox.DisplayMember = "MyKey"; // Just set the correct name of the properties 
    myListBox.ValueMember = "MyValue"; 
    this.myListBox.DataBind();         
}
Run Code Online (Sandbox Code Playgroud)