views:

33

answers:

2

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 ?

+1  A: 

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

Michael Goldshteyn
I have thought of that, but my items is dynamic in height. Can I calculate the height of each item in the listbox at runtime ?
driis
You can get the rendered height of each displayed item, but the method to do this escapes me at the moment...
Michael Goldshteyn
+1  A: 

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]);
Mick N
This works as intended :-)
driis