I have a WPF ListBox bound to an observable collection. When things are added to the collection, the listbox scroll position shifts by the size of the added entries. I'd like to be able to preserve the scroll position, so that even as things are added to the list, the items currently in view don't move. Is there a way to accomplish this?
views:
699answers:
4I'm not sure if there's an override for that, but I doubt it.
When in doubt use manual binding? :-} Seriously, the default binding behavior will be - well - default, so if you need special behavior manual binding is a better choice. With manual binding you can save the scroll position and reset it after you've added the items.
Create a CollectionView. Try this:
private ObservableCollection<int> m_Values;
private CollectionView m_View;
private void Bind()
{
m_Values = new ObservableCollection<int>();
m_View = new CollectionView(m_Values);
MyListBox.ItemsSource = m_View;
}
private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine(m_View.CurrentItem);
Debug.WriteLine(m_View.CurrentPosition);
}
Do you control when things are added? I mean do you have one or two defined points where data gets changed? If so, one easy solution (perhaps not elegant) would be so have a local int variable to hold the current ListBox.SelectedIndex. Just before data changes, save the selectedIndex to this variable and after data is added, set the SelectedIndex of the listBox to the value of this variable.
Firstly find the current position by ListBox.SelectedIndex and then use ListBox.ScrollIntoView(/* Current Index */). Even if the new items are added in list your current position and view will be the same.