Возможные решения:
1) Делать перед добавлением нового элемента
collection.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;
2) В основном попробуйте добавить элементы перед созданием группировки и сортировки:
var collection = new ListCollectionView(new List<Test>());
collection.AddNewItem(new Test() { Name = "Bob", IsTrue = false });
collection.CommitNew();
collection.SortDescriptions.Add(new SortDescription("IsTrue",
ListSortDirection.Ascending));
collection.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
Анализ:
После копания в .NET Reflector метод CommitNew()
имеет следующую проверку:
// !!! When you've added GroupDescription this.IsGrouping becomes true!
if (this.IsGrouping)
{
this.CommitNewForGrouping();
}
Поскольку вы добавили GroupDescription, оно будет зафиксировано для группировки:
private void CommitNewForGrouping()
{
int num;
// !!! I believe it is None by default
switch (this.NewItemPlaceholderPosition)
{
case NewItemPlaceholderPosition.AtBeginning:
num = 1;
break;
case NewItemPlaceholderPosition.AtEnd:
num = this._group.Items.Count - 2;
break;
default:
// !!! Since you've not added groups -1 would be assigned to num
num = this._group.Items.Count - 1;
break;
}
int index = this._newItemIndex;
object item = this.EndAddNew(false);
// This method will call RemoveAt(num) where num == -1 in your case
this._group.RemoveSpecialItem(num, item, false);
this.ProcessCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,
item, index));
}
internal void RemoveSpecialItem(int index, object item, bool loading)
{
...
// will fail since index always -1
base.ProtectedItems.RemoveAt(index);
...
}
У LCV есть закрытый метод ProcessCollectionChangedWithAdjustedIndex
, который настраивает индекс в различных сценариях, но он не вызывается, пока добавляется новый элемент с включенной группировкой, я не уверен, почему так выглядит, что это по замыслу (?!) вручную укажите заполнитель AtBeginning
для новых элементов.