ListViewItem隐式添加ListViewSubItem

时间:2016-12-01 11:13:20

标签: c# listview

假设我使用以下代码构建ListView

ListViewItem item1 = new ListViewItem();
item1.Text = "item1";
item1.SubItems.Add(new ListViewItem.ListViewSubItem(item1, "subitem1"));
item1.SubItems.Add(new ListViewItem.ListViewSubItem(item1, "subitem2"));
listView1.Items.Add(item1);

但实际上它会像这样创建3 ListViewSubItem

ListViewItem 
     |
     -------------------------------------
     |                  |                |
ListViewSubItem  ListViewSubItem  ListViewSubItem
 (Text=item1)    (Text=subitem1)  (Text=subitem2)

在我的真实计划中,我使用源自ListViewItem.ListViewSubItemOwnerDraw = true

的自定义子项
ListViewItem item1 = new ListViewItem();
CustomListViewSubItem subitem1 = new CustomListViewSubItem(item1, "subitem1");
CustomListViewSubItem subitem1 = new CustomListViewSubItem(item1, "subitem1");
listView1.Items.Add(item1);

以上行为在DrawSubItems事件中投射时会破坏所有逻辑:

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    ListViewItem item = e.Item;
    ListViewItem.ListViewSubItem subitem = item.SubItems[e.ColumnIndex];
    CustomListViewSubItem customsubitem = (CustomListViewSubItem)subitem; // <- System.InvalidCastException here
    ...
}

当然,只有第一个子项目才会失败,事实上它是项目但不是我想要的。我怎样才能避免这种行为,只创建我需要的2个子项?

1 个答案:

答案 0 :(得分:1)

未经测试但可能有效:
通过在空集合上调用listView.SubItems,它会自动添加一个“默认”元素。我的建议是在添加元素后删除第一个元素:

listView.SubItems.Add(new MeListViewSubItem( ... ) );
listView.SubItems.RemoveAt(0);

来自ReferenceSource

    /// <include file='doc\ListViewItem.uex' path='docs/doc[@for="ListViewItem.SubItems"]/*' />
    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    [
    SRCategory(SR.CatData),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),        
    SRDescription(SR.ListViewItemSubItemsDescr),
    Editor("System.Windows.Forms.Design.ListViewSubItemCollectionEditor, " + AssemblyRef.SystemDesign,typeof(UITypeEditor)),
    ]
    public ListViewSubItemCollection SubItems {
        get {
            if (SubItemCount == 0) {
                subItems = new ListViewSubItem[1];
                subItems[0] = new ListViewSubItem(this, string.Empty);                        
                SubItemCount = 1;
            }

            if (listViewSubItemCollection == null) {
                listViewSubItemCollection = new ListViewSubItemCollection(this);
            }
            return listViewSubItemCollection;
        }
    }