问题
I have a ListView that shows around 300 items. When something is changed and I need to repopulate the list, I would like the scroll position to be unchanged, so the same items are still visible and in the same position in the list. The "EnsureVisible" method sucks since it is satisified with "Visible", not the same position (the result is that the item of interest is always scrolled to the bottom of the list).
My solution to the problem is to to save the (my) "ID" of the List->TopItem, refill the list and then call List->TopItem = newItemWithSameID (needs to be set twice to work for some reason). This works as a charm for basic "ungrouped" lists.
BUT - if the List has "ShowGroups = true" this will not work. The property TopItem will then always be the first item in the list, not the first VISIBLE item as the documenation says.
Is there a solution? I googled around and found another lost soul having the same problem. He had a rather funny discussion on Microsoft support about it, without success.(http://social.msdn.microsoft.com/Forums/en/winforms/thread/8a81c5a6-251c-4bf9-91c5-a937b5cfe9f3).
So - my question is: is there a workaround? I really need the list to be grouped, and I really hates when the list jumps around when something is changed.
I won't paste any code here, since all the code you need to reproduce this is in the discussion above.
Thanks alot!
回答1:
Here's a workaround that I have used for this problem:
public ListViewItem RealTopItem
{
int i = 0;
while (i < Items.Count && !ClientRectangle.Contains(Items[i].Bounds))
i++;
return Items[i];
}
Unfortunately, it just recently failed for a customer in the while-statement after having worked for a year in my code. In my troubleshooting, I first tried to deactivate groups, and the problem went away. Then as I reactivated groups again, the problem never reoccured. I have no idea right now what could be wrong there.
来源:https://stackoverflow.com/questions/8935186/net-topitem-property-of-listview-fails-with-showgroups-true