简体   繁体   English

Winforms combobox 显示 class 名称而不是实际 object 名称

[英]Winforms combobox displaying class names instead of actual object name

I have this class that contains a static list我有这个 class 包含一个 static 列表

public class TypeList
{
    public string Name;
    public string NameTag;

    public TypeList(string Name, string NameTag)
    {
        this.Name = Name;
        this.NameTag = NameTag;
    }

    public static List<TypeList> DataType = new List<TypeList>() {
        new TypeList("DataType","-1"),
        new TypeList("OpOne","1"),
        new TypeList("OpTwo","2"),
    };
}

I then put the static list called DataType into a combobox:然后我将名为 DataType 的 static 列表放入 combobox 中:

public void RefreshList()
{
    List<TypeList> data = new List<TypeList>();
    data = TypeList.DataType;

    typeCB.DataSource = data;
    typeCB.DisplayMember = "Name";
    typeCB.ValueMember = "NameTag";
    typeCB.SelectedValue = -1;
    typeCB.SelectedText = "Select DataType";
}

However, when I run it, all I get are the classnames in my combobox.但是,当我运行它时,我得到的只是 combobox 中的类名。 Is something wrong with my code?我的代码有问题吗? I tried to do我试着做

data.Select(x=>x.Name).ToList() data.Select(x=>x.Name).ToList()

But that just gives me the name portion.但这只是给了我名字部分。

I might be wrong, but based on the Documentation and Example it might be that this Feature only works with public property getters, not public fields:我可能错了,但根据文档和示例,此功能可能仅适用于公共属性获取器,而不适用于公共字段:

Gets or sets the property to display for this ListControl.获取或设置要为此 ListControl 显示的属性

public class USState
{
    private string myShortName;
    private string myLongName;

    public USState(string strLongName, string strShortName)
    {

        this.myShortName = strShortName;
        this.myLongName = strLongName;
    }

    public string ShortName
    {
        get
        {
            return myShortName;
        }
    }

    public string LongName
    {

        get
        {
            return myLongName;
        }
    }

}

Of course I would also advise against making the list a part of the Type class.当然,我也建议不要将列表作为 class 类型的一部分。 A simple Programm scope static would be better.一个简单的程序 scope static 会更好。 If that is the case and as autoproties have have become a thing by now, this should be enough of a fix:如果是这样的话,并且现在自动特性已经成为一种东西,这应该足以解决问题:

public class Type
{
public string Name { private set; get } ;
public string NameTag {private set; get };

    public TypeList(string Name, string NameTag)
    {
        this.Name = Name;
        this.NameTag = NameTag;
    }

}



//use in the class of main, the form or some similar central point
static List<Type> TypeList = new List<Type>();

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

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