简体   繁体   English

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

[英]C#: How to bind to ListBox DisplayMember and ValueMember result from class method?

I'm trying to create ListBox where I will have key-value pair. 我正在尝试创建将具有键值对的ListBox。 Those data I got from class which provides them from getters. 我从课堂上获得的数据,这些数据是由吸气剂提供的。

Class: 类:

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

    public myClass() { }

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

    public int GetValue()
    {
        return this.value;
    }
}

Program: 程序:

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

It's similar to this topic [ Cannot do key-value in listbox in C# ] but I need to use class that returns values from methods. 它类似于本主题[ 无法在C#的列表框中执行键值 ],但我需要使用从方法返回值的类。

Is it possible to do somewhat simple or I'd better rework my thought flow (and this solution) completely? 是否可以做一些简单的事情,或者我最好完全重做我的思想流程(以及此解决方案)?

Thank you for advice! 谢谢你的建议!

The DisplayMember and ValueMember properties require the name (as a string) of a property to be used. DisplayMemberValueMember属性要求使用属性的名称(作为字符串)。 You can't use a method. 您不能使用一种方法。 So you have two options. 因此,您有两个选择。 Change you class to return properties or make a class derived from myClass where you could add the two missing properties 更改您的类以返回属性或制作一个派生自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);}
    }
}

Now that you have made these changes you could change your list with the new class (but fix the initialization) 现在,您已经进行了这些更改,可以使用新的类更改列表(但可以修复初始化)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM