Is it possible to have a ComboBox DisplayMember set to a property of an object in a list?

孤街浪徒 提交于 2019-12-12 22:16:23

问题


I have a ComboBox being populated where each object in ComboBox.Items is a List of objects. Currently the ComboBox displays "(Collection)" for each Item.

Is it possible to have the ComboBox display a member of the first object in the List that comprises an Item of the ComboBox?

I am currently populating the ComboBox items by the following:

foreach(List<SorterIdentifier> sorterGroup in m_AvailableSorterGroups)
{
    // There are conditions that may result in the sorterGroup not being added
    comboBoxSorterSelect.Items.Add(sorterGroup);
}

//comboBoxSorterSelect.DataSource = m_AvailableSorterGroups; // Not desired due to the comment above.
//comboBoxSorterSelect.DisplayMember = "Count"; //Displays the Count of each list.

The value that I would like to have displayed in the ComboBox can be referenced with:

((List<SorterIdentifier>)comboBoxSorterSelect.Items[0])[0].ToString();
((List<SorterIdentifier>)comboBoxSorterSelect.Items[0])[0].DisplayName; // public member

回答1:


You can create an object wrapper and override the ToString() method:

public class ComboBoxSorterIdentifierItem
{

  public List<SorterIdentifier> Items { get; }

  public override string ToString()
  {
    if ( Items == null || Items.Count == 0) return "";
    return Items[0].ToString();
  }

  public BookItem(List<SorterIdentifier> items)
  {
    Items = items;
  }

}

You should override the SorterIdentifier.ToString() too to return what you want like DisplayName.

Now you can add items in the combobox like this:

foreach(var sorterGroup in m_AvailableSorterGroups)
{
  item = new ComboBoxSorterIdentifierItem(sorterGroup);
  comboBoxSorterSelect.Items.Add(item);
}

And to use the selected item for example, you can write:

... ((ComboBoxSorterIdentifierItem)comboBoxSorterSelect.SelectedItem).Item ...


来源:https://stackoverflow.com/questions/58203681/is-it-possible-to-have-a-combobox-displaymember-set-to-a-property-of-an-object-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!