I observed that providing an empty list (i.e. an ObservableCollection<T>, in my case) to the ListCollectionView construtor (having a SortDescription criteria attached to it) does not sort new items adding to the observable collection. Although, if the same intial list is provided not empty, then the ListCollectionView sorts new items implicitly (i.e. automatically) no matter if manipulations lead the observable collection empty again.
That is, having one item in the source list when constructing the collection view, deleting the item from the source list, and then adding new items, results in a ListViewCollection sorted as expected.
It looks like that the ListViewCollection does not attach to the CollectionChanged event if the list empty (I did not investigated deeper using Reflector).
Here is a code snippet showing the unexpected behavior:
privateclassItem{
internalstring Title { get; privateset; } internal Item(string title) {
Title = title;
}
}
publicvoid TestListCollectionViewBug(){
var collection1 = newObservableCollection<Item> { newItem("X") }; var collection2 = newObservableCollection<Item>(); var view1 = newListCollectionView(collection1);
var view2 = newListCollectionView(collection2);
view1.SortDescriptions.Add(newSortDescription("Title", ListSortDirection.Ascending));
view2.SortDescriptions.Add(newSortDescription("Title", ListSortDirection.Ascending));
collection1.Add(newItem("C")); collection2.Add(newItem("C"));
collection1.Add(newItem("A")); collection2.Add(newItem("A"));
collection1.Add(newItem("B")); collection2.Add(newItem("B"));
Debug.Assert(((Item)view1.GetItemAt(0)).Title == "A");
Debug.Assert(((Item)view1.GetItemAt(1)).Title == "B");
Debug.Assert(((Item)view1.GetItemAt(2)).Title == "C");
Debug.Assert(((Item)view1.GetItemAt(3)).Title == "X");
Debug.Assert(((Item)view2.GetItemAt(0)).Title == "B");
Debug.Assert(((Item)view2.GetItemAt(1)).Title == "A");
Debug.Assert(((Item)view2.GetItemAt(2)).Title == "C");
}