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) 请建议。
答案 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) { ... }