C# 如何在虚拟模式下异步填充 ListView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/336901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:45:07  来源:igfitidea点击:

How do I populate a ListView in virtual mode asynchronously?

c#winformslistviewasynchronousvirtualmode

提问by Simon

I'd like to display records from our database in a listview - but retrieves can take a long time. I can use RetrieveVirtualItem to tell me when a new ListViewItem is needed, add a dummy item, and start a retrieve; but what do I do with the record when the database returns it? I can't update the ListView's Items collection while the ListView is in VirtualMode. Is there a way to tell the ListView to reload an item? Or can I just keep a reference to the ListViewItem and populate that? If neither of those would work, how else could I populate a ListView in virtual mode asynchronously?

我想在列表视图中显示我们数据库中的记录 - 但检索可能需要很长时间。我可以使用 RetrieveVirtualItem 来告诉我什么时候需要一个新的 ListViewItem,添加一个虚拟项,然后开始检索;但是当数据库返回记录时我该怎么办?当 ListView 处于 VirtualMode 时,我无法更新 ListView 的 Items 集合。有没有办法告诉 ListView 重新加载项目?或者我可以保留对 ListViewItem 的引用并填充它吗?如果这些都不起作用,我还能如何在虚拟模式下异步填充 ListView ?

采纳答案by Dave R.

Your RetrieveVirtualItem handler will be called when the ListView needs updating. If your data is not available yet and you cannot wait, then you will have to create a dummy item (not handling RetrieveVirtualItem will raise an exception).

当 ListView 需要更新时,将调用您的 RetrieveVirtualItem 处理程序。如果您的数据尚不可用且您无法等待,那么您将不得不创建一个虚拟项目(不处理 RetrieveVirtualItem 将引发异常)。

Once your data is ready, you can invalidate the control - this will call RetrieveVirtualItem again for each of the visible items. As an alternative to invalidating the whole control, you can control which items are to be redrawn by using the RedrawItems method of the ListView control, which works in virtual and regular modes:

一旦您的数据准备好,您就可以使控件无效 - 这将再次为每个可见项目调用 RetrieveVirtualItem。作为使整个控件无效的替代方法,您可以使用 ListView 控件的 RedrawItems 方法来控制要重绘哪些项目,该方法在虚拟和常规模式下工作:

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.redrawitems.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.redrawitems.aspx

It sounds like it may be worth downloading your records in batches if it's due to take a while. Also, if your database operations are expensive, it's well worth investigating caching your ListItems (there's a CacheVirtualItems event you'll need to handle):

如果需要一段时间,听起来可能值得分批下载您的记录。此外,如果您的数据库操作很昂贵,那么研究缓存您的 ListItems 是非常值得的(您需要处理一个 CacheVirtualItems 事件):

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.cachevirtualitems.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.cachevirtualitems.aspx

I hope this helps.

我希望这有帮助。