如何在listviewitem处于虚拟模式时设置topview属性?

时间:2015-02-08 04:34:10

标签: listview c#-3.0 listviewitem virtualmode

public new int VirtualListSize
    {
        get { return base.VirtualListSize; }
        set
        {
            // If the new size is smaller than the Index of TopItem, we need to make
            // sure the new TopItem is set to something smaller.
            if (VirtualMode &&
                View == View.Details &&
                TopItem != null &&
                value > 0 &&
                TopItem.Index > value - 1)
            {
                TopItem = Items[value - 1];
            }

            base.VirtualListSize = value;
        }
    }

我正在尝试设置listview的topitem属性,但是在虚拟模式下项目被禁用。因此,任何试图在虚拟模式下访问它的代码都会引发无效操作异常。当我尝试逐行调试时不会发生异常。如果我对行TopItem=Items[value-1]发表评论,它不会抛出任何异常。

System.InvalidOperationException:在VirtualMode中,ListView RetrieveVirtualListItem事件需要每个ListView列的列表视图SubItem。    在System.Windows.Forms.ListView.WmReflectNotify(消息& m)    在System.Windows.Forms.ListView.WndProc(消息& m)    在System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)  请建议。

1 个答案:

答案 0 :(得分:2)

当虚拟列表大小变小时,您不需要更改TopItem。 .NET ListView已经做到了。根据dotPeek反汇编程序:

public int VirtualListSize { 
    ... 
    set {
        ...
        bool keepTopItem = this.IsHandleCreated && VirtualMode && this.View == View.Details && !this.DesignMode; 
        int topIndex = -1;
        if (keepTopItem) { 
            topIndex = unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); 
        }

        virtualListSize = value;

        if (IsHandleCreated && VirtualMode && !DesignMode)
            SendMessage(NativeMethods.LVM_SETITEMCOUNT, virtualListSize, 0); 

        if (keepTopItem) { 
            topIndex = Math.Min(topIndex, this.VirtualListSize - 1); 
            // After setting the virtual list size ComCtl makes the first item the top item.
            // So we set the top item only if it wasn't the first item to begin with. 
            if (topIndex > 0) {
                ListViewItem lvItem = this.Items[topIndex];
                this.TopItem = lvItem;
            } 
        }
    } 
}

这样做的问题在于,根据我的经验,在虚拟列表视图上设置TopItem是一项容易出错的活动。在我的代码中,我有这个块:

// Damn this is a pain! There are cases where this can also throw exceptions!
try {
    this.listview.TopItem = lvi;
}
catch (Exception) {
    // Ignore any failures
}

由于设置TopItem有时会抛出异常,这意味着有时设置VirtualListSize同样会抛出异常。

其他要点

即使在虚拟模式下,您也可以通过索引访问Items集合。所以,这很好(假设列表不是空的):

this.listview1.TopItem = this.listview1.Items[this.listview1.Items.Count - 1];

无法在虚拟模式下迭代Items集合。这将抛出异常:

foreach (ListViewItem item in this.listview1.Items) { ... }