1
votes

I am using Silverlight 4 and the MVVM pattern. In my view I have a ListBox that has its ItemsSource and SelectedItem properties bound to properties in the view model.

<ListBox ...
    ItemsSource="{Binding AllItems, Mode=TwoWay}"
    SelectedItem="{Binding SelectedItem, Mode=TwoWay}">

In some circumstances when this view is loaded I want a particular item selected; in these cases I simply set the SelectedItem property in the view model's constructor accordingly. This works splendidly in that when the view is loaded the desired item is selected.

However, if there are many items in the ListBox such that there are vertical scrollbars the ListBox does not automatically scroll down to the selected list item.

Is it possible in Silverlight, using the MVVM pattern, to have the ListBox auto-scroll to the selected item when the view is loaded?

Thanks

Note: Silverlight 5 does not exhibit this problem. This must be a bug (or "feature") of Silverlight 4. My workaround below works in SL5, but is not needed...

1

1 Answers

1
votes

I ended up going the following route, which seems to bend the MVVM pattern but not break it since this is a UI-related issue, after all.

In the view (a child window) I have an event handler for the Loaded event and in there I do this:

if (viewModel.SelectedItem != null)
{
    myListBox.UpdateLayout();
    myListBox.ScrollIntoView(viewModel.SelectedItem);
}

If anyone has any suggestions feel free to give them, I'm a total Silverlight noob.