c# - 是否可以将 ComboBox DisplayMember 设置为列表中对象的属性?

标签 c# list winforms combobox

我有一个正在填充的 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/

相关文章:

c# - 如何在 Windows 窗体中显示组合框所选项目的全文?

winforms - 根据与远边缘不同的约束来调整无边界形式的大小?

c# - 调试 > Windows > 输出此控制台消息是什么意思?

c# - 如何快速查看服务时间

c# - 参数字典包含参数的空条目,但参数存在

python - 列表中的差异 - Python - 语法解释

Python 在打印时对列表进行换行/格式化

c# - 从静态方法线程安全返回引用吗?

c# - .net Core EF - 按字符串名称或类型动态添加到 DbSet

python - 在 Python 中合并/添加列表