I currently have a ListBox whose ItemsSource collection is bound to a property on my viewmodel, of type IEnumerable. When that preoprty's reference changes, the ListBox updates as expected, however I have a problem in that if I have a large collection of items and scroll to the bottom of the ListBox, and then change the reference to another collection containing, say, 1 item, the ListBox view is blank and no scrollbar is displayed. I have to then scroll the listbox up with the mouse wheel, until the 1 item comes into view.
So, what I think I'm after, is a way of resetting the scroll position of the ListBox to the top, whenever the ItemsSource property changes, so that something is always displayed no matter how large or small the collection.
Best Answer
I'm unable to reproduce your problem (for me, the
ListBox
is scrolled to the last item in the new collection when changingItemsSource
). Anyway, to scroll theListBox
to the top every time itsItemsSource
changes you can use some code behind. First listen to changes in theItemsSourceProperty
and then scroll theListBox
to the top once its items has been generatedUpdate
Made an attached behavior that does this instead to avoid code behind. It can be used like this
ScrollToTopBehavior
And an implementation of GetVisualChild