Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight maintain ListBox scroll position

I have a ListBox control that I use an ObservableCollection to add items to in my ViewModel however I notice the ListBox doesn't maintain the scroll position as I would expect.

I'm new to Silverlight and opted to go with MVVM but I can't figure out to do it. The scenario is as follows:

  • Get ListBox scroll position (needs to access xaml control, but insides ViewModel?)
  • Add item to ObservableCollection (done, just via Dispatcher.CheckBeginInvokeOnUI in the ViewModel, the ListBox control's ItemSource is bound to it).
  • Set ListBox scroll position (again needs access to xaml control from within ViewModel?)

I've found this answer here: Restoring exact scroll position of a listbox in Windows Phone 7

And with a bit of modifying I think the vertical scroll position can be fetched and set via:

ScrollViewer sv = TimelineTweets.Descendents().OfType<ScrollViewer>().FirstOrDefault();
double startOffset = sv.VerticalOffset;
sv.ScrollToVerticalOffset(startOffset);

But how would I even go about this with MVVM and Silverlight in general, very confused.

like image 615
Phil Avatar asked Feb 01 '26 07:02

Phil


1 Answers

I would suggest that scroll position is something for UI so handle it in UI code behind. This will not break MVVM because you still handle all that in your ViewModel.

like image 69
kalvis Avatar answered Feb 03 '26 23:02

kalvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!