3
votes

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.

2

2 Answers

1
votes

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.

0
votes

you can store it using

(DataContext as VM).ScrollVOffset=sv.VerticalOffset 

inside your view. Where VM is the ViewModel class and ScrollVOffset is property of ViewModel class.