我有一个正在填充的 ComboBox,其中 ComboBox.Items 中的每个对象都是对象列表。目前,组合框为每个项目显示“(集合)”。
是否可以让组合框显示列表中包含组合框项目的第一个对象的成员?
我目前正在通过以下方式填充组合框项目:
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.
我想在组合框中显示的值可以引用:
((List<SorterIdentifier>)comboBoxSorterSelect.Items[0])[0].ToString();
((List<SorterIdentifier>)comboBoxSorterSelect.Items[0])[0].DisplayName; // public member
最佳答案
您可以创建一个对象包装器并重写 ToString()
方法:
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
。
现在您可以在组合框中添加项目,如下所示:
foreach(var sorterGroup in m_AvailableSorterGroups)
{
item = new ComboBoxSorterIdentifierItem(sorterGroup);
comboBoxSorterSelect.Items.Add(item);
}
例如,要使用所选项目,您可以编写:
... ((ComboBoxSorterIdentifierItem)comboBoxSorterSelect.SelectedItem).Item ...
关于c# - 是否可以将 ComboBox DisplayMember 设置为列表中对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203681/