Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freezing a listboxitem while items are being added

Tags:

c#

wpf

We have a ListBox that has a number of items. Items are inserted into the ListBox via an ObservableCollection. Some of these items can be edited right in the ListBox. However, if an item is added at an index < the edited item's index, the entire content of the ListBox moves down.

What we'd like to do is the following: if an item is in edit mode, we'd like to freeze its position on the screen. It is fine if items are added to the collection and the UI around the item changes. But the position of the item should remain constant on the screen.

The only thing I've been able to do so far is attach to the ScrollChanged event and, at most, use either BringIntoView or ScrollIntoView methods to ensure that the item is always displayed somewhere in the UI, but I am unable to lock down its position.

Has anyone done something like this and help out?

like image 776
Szymon Rozga Avatar asked Mar 11 '10 21:03

Szymon Rozga


1 Answers

I think the following would solve your problem:

  1. When entering edit mode, keep a reference to the object you're editing, its index in listbox and the ScrollViewer's HorizontalOffset.

  2. In a handler to the ObservableCollection.CollectionChanged event find the new index of the object you editing, if the index changed, swap the edited item with the one now taking it's place (or some other logic if you want to keep a certain order). Then if the ScrollViewer.HorizontalOffset changed, move it back to the said offset.

This will make sure the item you're editing will always stay in the exact same place in the list and in the UI.

Hope this help you out.

like image 161
sprite Avatar answered Sep 21 '22 19:09

sprite