问题
I want to use a property of an object that's inside an object. Is there a way to achieve this?
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);
Thanks.
回答1:
Have a look at this question, it is essentially asking the same thing - the principle does not change between DataGridView
and ListBox
. Short answer: it's possible, but convoluted.
回答2:
How about you subclass WebProxy
to, for instance, WebProxyEx
and implement the IList interface which sort of(expects an object that implements the IList or IListSource interfaces) is a pre-requisite to use the .DataSource
property of listbox. Like following:
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);
}
...
And use it like:
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.
}
Gives following output in the listbox:
127.0.0.1
来源:https://stackoverflow.com/questions/4273917/use-a-object-property-as-the-displaymember-in-listbox