问题描述
我正在填充一个ComboBox,其中ComboBox.Items中的每个对象都是一个对象列表.当前,组合框为每个项目显示(集合)".
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.
是否可以让ComboBox显示列表中包含ComboBox项的第一个对象的成员?
Is it possible to have the ComboBox display a member of the first object in the List that comprises an Item of the ComboBox?
我目前正在通过以下方式填充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.
我想在ComboBox中显示的值可以通过以下方式引用:
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
推荐答案
您可以创建对象包装并覆盖ToString()
方法:
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;
}
}
您也应该覆盖SorterIdentifier.ToString()
以返回所需的内容,如DisplayName
.
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 ...
这篇关于是否可以将ComboBox DisplayMember设置为列表中对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!