开发者

Silverlight maintain ListBox scroll position

开发者 https://www.devze.com 2023-02-17 04:06 出处:网络
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 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:

ScrollView开发者_如何学Goer 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号