tags:

views:

301

answers:

4

I have a silverlight control (View) which displays a list of items in a specified property of the datacontext (viewmodel).

What I need is for the scrollviewer in my control to scroll to the top or bottom depending on where the latest item has been added to the list. (It'll always be either the beginning or the end of the list, I don't need to worry about middle of list insertions.)

In WPF i'd just use the DataContextChanged event to start listening to the viewmodel, but in silverlight that event is internal.

Any ideas on how to tackle this?

A: 

In place of DataContextChanged in WPF , you can use CollectionChanged event of ObservableCollection. In the collection changed you will get to know the NewItem Index.

Jobi Joy
Not useful for a Silverlight question.
Ray Booysen
A: 

I can't use the CollectionChangedEvent of ObservableCollection since I need the DataContextChanged event to get the DataContext which holds the Collection in the first place.

Graeme Bradbury
+1  A: 

A good starting point is Attached Behaviors on CodeProject.

A useful behavior would watch the ListBox.ItemsSource and attach to the observable collection when set. On the collection changed event, use ListBox.ScrollIntoView to display the changed item.

Doug Ferguson
A: 

Would you not do this in the ViewModel?

Whatever ViewModel has the ObservableCollection, expose a property of type T named SelectedItem and whenever the ObservableCollection changes with a new item, the CollectionChanged event will allow you to set the SelectedItem property. Once this is done, wire up the SelectedItem in the control to this property on your ViewModel.

This will obviously only work with controls like ListBox where a SelectedItem property exists.

Ray Booysen