如何从类方法中绑定ListBox的DisplayMember和ValueMember结果

本文关键字:DisplayMember ValueMember 结果 ListBox 绑定 类方法 | 更新日期: 2023-09-27 18:16:04

我试图创建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;
    }
}

计划:

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();
}

它类似于这个主题[不能在c#的列表框中做键值],但我需要使用从方法返回值的类。

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

谢谢你的建议!

如何从类方法中绑定ListBox的DisplayMember和ValueMember结果

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);}
    }
}

现在你已经做了这些改变,你可以用新的类改变你的列表(但修复初始化)

// 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();         
}