CommunityToolkit/WindowsCommunityToolkit
GitHub で見る[Bug] Exception is thrown when removing the last item in a group in ObservableGroupedCollection bound to a DataGrid
Open
#4,473 opened on 2022年2月1日
DataGrid :capital_abcd:bug :bug:controls :control_knobs:help wanted
説明
Description
When the item at the last index of an ObservableGroup that is in an ObservableGroupedCollection bound via a CollectionViewSource to a DataGrid is removed, an ArgumentOutOfRangeExcpetion is thrown.
Short example:
var list = new List<int> { 1, 1, 1, 2, 3 };
var ogc = new ObservableGroupedCollection<int,int>( list.GroupBy( x => x ) );
var cvs = new CollectionViewSource { Source = ogc, IsSourceGrouped = true };
ogc[0].RemoveAt( ogc[0].Count-1 ); // works fine
var myDataGrid = new DataGrid();
myDataGrid.ItemsSource = cvs.View;
ogc[0].RemoveAt( ogc[0].Count-1 ); // ArgumentOutOfRangeExcpetion
Expected behavior
No exception should be thrown. The DataGrid should remove the row, and if the row was selected, either select the next or previous row, or set selection to empty.
Partial fix
The DataGrid should check that the index is still valid before trying to fetch the value from the ObservableGroup.
Workaround
Wrapping the Remove or RemoveAt in a try/catch block and catching the ArgumentOutOfRangeExcpetion mitigates the issue.
try
{
ogc[0].RemoveAt( ogc[0].Count-1 ); // ArgumentOutOfRangeExcpetion
}
catch ( ArgumentOutOfRangeExcpetion )
{
//todo: log the exception
}