// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace CommunityToolkit.Common.Collections;
///
/// An observable group.
/// It associates a to an .
///
/// The type of the group key.
/// The type of the items in the collection.
[DebuggerDisplay("Key = {Key}, Count = {Count}")]
public class ObservableGroup : ObservableCollection, IGrouping, IReadOnlyObservableGroup
where TKey : notnull
{
///
/// The cached for
///
private static readonly PropertyChangedEventArgs KeyChangedEventArgs = new(nameof(Key));
///
/// Initializes a new instance of the class.
///
/// The key for the group.
public ObservableGroup(TKey key)
{
this.key = key;
}
///
/// Initializes a new instance of the class.
///
/// The grouping to fill the group.
public ObservableGroup(IGrouping grouping)
: base(grouping)
{
this.key = grouping.Key;
}
///
/// Initializes a new instance of the class.
///
/// The key for the group.
/// The initial collection of data to add to the group.
public ObservableGroup(TKey key, IEnumerable collection)
: base(collection)
{
this.key = key;
}
private TKey key;
///
/// Gets or sets the key of the group.
///
public TKey Key
{
get => this.key;
set
{
if (!EqualityComparer.Default.Equals(this.key!, value))
{
this.key = value;
OnPropertyChanged(KeyChangedEventArgs);
}
}
}
///
object IReadOnlyObservableGroup.Key => Key;
}