Skip to content

Commit c85af73

Browse files
committed
Fixed a small bug, minor code tweaks
1 parent a3b0ba6 commit c85af73

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

Microsoft.Toolkit/Collections/ReadOnlyObservableGroupedCollection.cs

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ public ReadOnlyObservableGroupedCollection(IEnumerable<IGrouping<TKey, TValue>>
4949

5050
private void OnSourceCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
5151
{
52-
// Even if the NotifyCollectionChangedEventArgs allows multiple items, the actual implementation is only
53-
// reporting the changes one by one. We consider only this case for now.
52+
// Even if NotifyCollectionChangedEventArgs allows multiple items, the actual implementation
53+
// is only reporting the changes one by one. We consider only this case for now.
5454
if (e.OldItems?.Count > 1 || e.NewItems?.Count > 1)
5555
{
5656
static void ThrowNotSupportedException()
@@ -65,28 +65,33 @@ static void ThrowNotSupportedException()
6565
ThrowNotSupportedException();
6666
}
6767

68-
ObservableGroup<TKey, TValue>? newItem = e.NewItems?.Cast<ObservableGroup<TKey, TValue>>()?.FirstOrDefault();
69-
70-
if (newItem is null)
71-
{
72-
return;
73-
}
74-
7568
switch (e.Action)
7669
{
77-
case NotifyCollectionChangedAction.Add:
78-
Items.Insert(e.NewStartingIndex, new ReadOnlyObservableGroup<TKey, TValue>(newItem));
70+
case NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Replace:
71+
72+
// We only need to find the new item if the operation is either add or remove. In this
73+
// case we just directly find the first item that was modified, or throw if it's not present.
74+
// This normally never happens anyway - add and replace should always have a target element.
75+
ObservableGroup<TKey, TValue> newItem = e.NewItems!.Cast<ObservableGroup<TKey, TValue>>().First();
76+
77+
if (e.Action == NotifyCollectionChangedAction.Add)
78+
{
79+
Items.Insert(e.NewStartingIndex, new ReadOnlyObservableGroup<TKey, TValue>(newItem));
80+
}
81+
else
82+
{
83+
Items[e.OldStartingIndex] = new ReadOnlyObservableGroup<TKey, TValue>(newItem);
84+
}
85+
7986
break;
8087
case NotifyCollectionChangedAction.Move:
88+
8189
// Our inner Items list is our own ObservableCollection<ReadOnlyObservableGroup<TKey, TValue>> so we can safely cast Items to its concrete type here.
8290
((ObservableCollection<ReadOnlyObservableGroup<TKey, TValue>>)Items).Move(e.OldStartingIndex, e.NewStartingIndex);
8391
break;
8492
case NotifyCollectionChangedAction.Remove:
8593
Items.RemoveAt(e.OldStartingIndex);
8694
break;
87-
case NotifyCollectionChangedAction.Replace:
88-
Items[e.OldStartingIndex] = new ReadOnlyObservableGroup<TKey, TValue>(newItem);
89-
break;
9095
case NotifyCollectionChangedAction.Reset:
9196
Items.Clear();
9297
break;

0 commit comments

Comments
 (0)