【问题标题】:Is it possible to have a ComboBox DisplayMember set to a property of an object in a list?是否可以将 ComboBox DisplayMember 设置为列表中对象的属性?
【发布时间】:2020-01-31 20:39:41
【问题描述】:

我有一个 ComboBox 正在填充,其中 ComboBox.Items 中的每个对象都是一个对象列表。目前,组合框为每个项目显示“(集合)”。

是否可以让 ComboBox 显示 List 中包含 ComboBox 项目的第一个对象的成员?

我目前正在通过以下方式填充 ComboBox 项:

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 中显示的值可以通过以下方式引用:

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

【问题讨论】:

    标签: c# list winforms combobox


    【解决方案1】:

    您可以创建一个对象包装器并覆盖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 ...
    

    【讨论】:

      【解决方案2】:

      我可以想出几种方法来做到这一点...您可以创建一个扩展 List&lt;T&gt; 的类,这样您就有机会定义要显示的值。

      public class SortedIdentifier
      {
          public string Name { get; set; }
      }
      
      public class SortedIdentifiers : List<SortedIdentifier>
      {
          public string SortedIdentifierDisplayValue
          {
              get { return this.FirstOrDefault()?.Name ?? "No Items"; }
          }
      }
      

      然后像这样使用新类:

      comboBox1.DisplayMember = "SortedIdentifierDisplayValue";
      
      var list = new SortedIdentifiers { new SortedIdentifier { Name = "John" } };
      comboBox1.Items.Add(list);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-03
        • 2012-01-06
        • 1970-01-01
        • 2011-02-11
        • 1970-01-01
        • 1970-01-01
        • 2013-11-12
        相关资源
        最近更新 更多