CommunityToolkit/WindowsCommunityToolkit

[Bug] Exception is thrown when removing the last item in a group in ObservableGroupedCollection bound to a DataGrid

Open

#4,473 创建于 2022年2月1日

在 GitHub 查看
 (2 评论) (0 反应) (0 负责人)C# (5,708 star) (1,403 fork)batch import
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
}

贡献者指南