I'm trying to implement the MVVM pattern in WPF. I've followed Jeremy Alles's Very simple MVVM demo application. I have a ListBox that has a binding to an ObservableCollection:
<ListBox
Name="myListBox"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Persons}">
<ListBox.ItemTemplate>
<DataTemplate>
<views:PersonsView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I added an ICollectionView to manage the selected item on the ListBox. It also allows me to have two buttons that allow me to select the previous and next items in the list.
private void GoToPrevious()
{
this.collectionView.MoveCurrentToPrevious();
}
private void GoToNext()
{
this.collectionView.MoveCurrentToNext();
}
It all works great, however, when the selected item is below the displayed area of the listbox, the listbox's scrollbar doesn't move accordingly.
How can I synchronize the scrollbar/display area of the ListBox with the selected item?
Best Answer
I've found the answer. I needed to use
The problem was that I didn't wanted to add any code-behind, as I am implementing MVVM.
The solution is using Attached Behaviors. Josh Smith has a great article about this: Introduction to Attached Behaviors in WPF.
I adedd a Setter to the style of the items in the ListBox:
And added the following class (only changed TreeView from Josh's article to ListBox):
It works!!