【问题标题】:Use a object property as the DisplayMember in ListBox使用对象属性作为 ListBox 中的 DisplayMember
【发布时间】:2010-11-25 05:07:40
【问题描述】:

我想使用对象内部的对象的属性。 有没有办法做到这一点?

WebProxy proxy = new WebProxy("127.0.0.1:80");
ListBox listBox = new ListBox();
listBox.DisplayMember = **"Address.Authority"**; //Note: Address.Authority is an property inside the WebProxy object
listBox.Items.Add(proxy);

谢谢。

【问题讨论】:

    标签: c# listbox listboxitem


    【解决方案1】:

    看看this question,它本质上是在问同样的事情——DataGridViewListBox之间的原理并没有改变。简短的回答:有可能,但令人费解。

    【讨论】:

    • 我使用了 OP 的 sabe 方法并创建了一个新对象,其中包含我的 WebProxy 对象和一个字符串,该字符串为我提供了代理的权限。感谢您的回答。
    【解决方案2】:

    您如何将WebProxy 子类化为例如WebProxyEx 并实现IList 接口,该接口有点(期望实现IList 或IListSource 接口的对象) - 使用列表框的.DataSource 属性的必要条件。如下:

    class WebProxyEx : WebProxy, IList
        {
            private object[] _contents = new object[8];
            private int _count;
    
            public WebProxy w;
    
            public WebProxyEx(string address)
            {
                _count = 0;
                w = new WebProxy(address);
                this.Add(w.Address.Authority);
            }
    ...
    

    并像这样使用它:

    ListBox lb;
    public Form1()
    {
        InitializeComponent();
        WebProxyEx w = new WebProxyEx("127.0.0.1:80");//Use your sub class
        lb = new ListBox();
        this.Controls.Add(lb);
    
        lb.DataSource = w;//assign the datasource.
        //lb.DisplayMember = "Address.Authority"; //Automatically gets added in the WebProxEx constructor.
    
    }
    

    在列表框中提供以下输出:

    127.0.0.1

    【讨论】:

    • 感谢您的回答。我不知道是否有必要实现 IList,因为我已经有一个 List 作为我的数据源。
    • 查看MSDN 获取.DataSource 属性; >实现IList接口的对象,如DataSet或Array
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多