/// <summary> /// Add an item to the desired subgroup(s) of the given group /// </summary> /// <param name="item">Item to add</param> /// <param name="group">Group to add item to</param> /// <param name="level">The level of grouping</param> /// <param name="loading">Whether we are currently loading</param> private void AddToSubgroups(object item, CollectionViewGroupInternal group, int level, bool loading) { object name = GetGroupName(item, group.GroupBy, level); ICollection nameList; if (name == UseAsItemDirectly) { // the item belongs to the group itself (not to any subgroups) if (loading) { group.Add(item); } else { int localIndex = group.Insert(item, item, ActiveComparer); int index = group.LeafIndexFromItem(item, localIndex); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } } else if ((nameList = name as ICollection) == null) { // the item belongs to one subgroup AddToSubgroup(item, group, level, name, loading); } else { // the item belongs to multiple subgroups foreach (object o in nameList) { AddToSubgroup(item, group, level, o, loading); } } }
//------------------------------------------------------ // // Private Methods // //------------------------------------------------------ /// <summary> /// Add an item to the subgroup with the given name /// </summary> /// <param name="item">Item to add</param> /// <param name="group">Group to add item to</param> /// <param name="level">The level of grouping.</param> /// <param name="name">Name of subgroup to add to</param> /// <param name="loading">Whether we are currently loading</param> private void AddToSubgroup(object item, CollectionViewGroupInternal group, int level, object name, bool loading) { CollectionViewGroupInternal subgroup; int index = (_isDataInGroupOrder) ? group.LastIndex : 0; // find the desired subgroup for (int n = group.Items.Count; index < n; ++index) { subgroup = group.Items[index] as CollectionViewGroupInternal; if (subgroup == null) { continue; // skip children that are not groups } if (group.GroupBy.NamesMatch(subgroup.Name, name)) { group.LastIndex = index; AddToSubgroups(item, subgroup, level + 1, loading); return; } } // the item didn't match any subgroups. Create a new subgroup and add the item. subgroup = new CollectionViewGroupInternal(name, group); InitializeGroup(subgroup, level + 1, item); if (loading) { group.Add(subgroup); group.LastIndex = index; } else { // using insert will find the correct sort index to // place the subgroup, and will default to the last // position if no ActiveComparer is specified group.Insert(subgroup, item, ActiveComparer); } AddToSubgroups(item, subgroup, level + 1, loading); }