简体   繁体   中英

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM