WP7: ListBox ScrollToTop?
In a Windows Phone 7 Silverlight app, I have a ListBox with a lot of items, that are generated dynamically from an external data source. One of these items will be "current", so I would like to programmatically scroll the ListBox so the item appears as the topmost visible item in the ListBox - so the user doesn't have to.
There is
listBox.ScrollIntoView(itemOfInterest开发者_开发知识库);
But that will only scroll so much, that the itemOfInterest
is at the bottom of the ListBox.
How can I programmatically scroll a ListBox, so a specific item appears at the top of the viewport ?
This can also be accomplished in a fairly straight forward manner by scrolling to the last item and then to the current item;
FirstListBox.ScrollIntoView(FirstListBox.Items[lastItemIndex]);
FirstListBox.ScrollIntoView(FirstListBox.Items[currentItemIndex]);
If you know the number of items visible in the list box, you can calculate the offset such that your item appears at the top, instead of the bottom, by scrolling into view the item at your item's location plus the number of items that the list box holds:
int itemToView=itemOfInterest+numItemsDisplayed;
You will of course need to check itemToView to make sure that it is not out of bounds, before calling listBox.ScrollIntoView().
listboxNews.ScrollIntoView(listboxNews.Items.First());
精彩评论