When I run the following test, I get an ArgumentOutOfRangeException:
[TestClass]
public class ReproduceException
{
[TestMethod]
public void Doesnt_throw_when_adding_to_grouped_collection()
{
var collection = new ListCollectionView(new List<Test>());
collection.SortDescriptions.Add(new SortDescription("IsTrue", ListSortDirection.Ascending));
collection.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
collection.AddNewItem(new Test() { Name = "Bob", IsTrue = false });
collection.CommitNew();
}
}
public class Test
{
public string Name { get; set; }
public bool IsTrue { get; set; }
}
An I get the following exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException()
at System.Collections.ObjectModel.Collection`1.RemoveAt(Int32 index)
at System.Windows.Data.ListCollectionView.CommitNewForGrouping()
at System.Windows.Data.ListCollectionView.CommitNew()
Am I perhaps not using the AddNewItem / CommitNew in the right way?
Possible solutions:
1) Do before adding a new item
2) Basically try out adding items before creation of the Grouping and Sorting:
Analysis:
After digging into the .NET Reflector,
CommitNew()method has following check:Since you’ve added GroupDescription it would commit for grouping:
LCV has private method
ProcessCollectionChangedWithAdjustedIndexwhich adjust index in different scenarios but it is not called whilst adding a new item with Grouping enables, I’m not sure why so looks like this is by design (?!) so you have manually specify placeholderAtBeginningfor the new items.