问题
I am trying to use a ListBox
to display a possibly infinite list of options to a user. Currently, I am simply cutting off the list at an arbitrary point, but I would like to allow the user to scroll down as far as they want. Also, I want to avoid generating non-visible items as much as possible as some computation has to be done to generate each item.
I tried writing listBox.ItemsSource = enumerable
expecting it to only ask the enumerable for visible items, but instead it tries to read all of the items which causes an infinite loop if there are infinitely many items.
My best idea is add a listener that gets notified whenever the ListBox
scrolls down and add new items such that there are always k
more items after the last item visible (where k
is probably the number of items visible at a time so Page Down works).
Is there some cleaner way to handle this?
回答1:
I would use a VirtualizingStackPanel
to make the UI draw fewer elements and then employ a Data Virtualization technique to limit the data you are keeping in memory. See more details here (especially Bea Stolnitz's blog entries referenced here).
来源:https://stackoverflow.com/questions/8691467/wpf-listbox-generate-items-as-user-scrolls