This project is read-only.

SortingReadOnlyContinuousCollection - ItemChanged

May 17, 2012 at 10:25 AM

When a property of an item changes, the SortingReadonlyCollection removes it and adds it again at the new position. Two events are sent to any subscriber.

Org Code in SortingReadOnlyContinousCollection: 

void OnItemChanged(object sender, INotifyPropertyChanged itemThatChanged)
{
TSource item = (TSource)itemThatChanged;
RemoveItemFromOutput(item);
InsertItemInSortOrder(item);
}

The problem occures, when you f.e bind a SortingReadonlyCollection to a grid. You lose the SelectedItem on the grid, as soon the collection gets reorderd - because the item is removed (for a short time) from the ItemsSource.

I think it would be better to do the removing/adding just within the SortingReadonlyCollection and fire one CollectionChanged event with the action Move (like the ObservableCollection<T> does)

New Code:

void OnItemChanged(object sender, INotifyPropertyChanged itemThatChanged)
{
TSource item = (TSource)itemThatChanged; 

 

int oldIndex = this.Output.IndexOf(item);
this 
.Output.RemoveAt(oldIndex);
int newIndex = this.Output.BinarySearch(item, this.KeySorter); 

if(newIndex < 0)
{
  newIndex = ~newIndex;
}

this
.Output.Insert(newIndex, item); 

if
(oldIndex == newIndex) 
 return;

FireMoveItem(item, newIndex, oldIndex);
}

 

Addidional Method in ReadOnlyContinousCollection: 

protected void FireMoveItem(T item, int index, int oldIndex)
{

FireCollectionChanged(new NotifyCollectionChangedEventArg(NotifyCollectionChangedAction

.Move, item, index, oldIndex));
}