You can use a macro ListView_SortGroupsfor this, for example. This macro expects you to have your own comparison function defined by the function prototype LVGroupCompare. In the following code, the groups are sorted by property Headerusing CompareText, but now you need to build your own comparison.
Forgot to note; no matter what you go to the last parameter of the Pointertype ListView_SortGroupsthat you get in LVGroupComparein the parameter pvData, since it will be a function for sorting groups of a certain kind of list, it is best to go directly to the Groupscollection of this list to simplify the manipulation.
Since there is no direct way to find a list view group by group ID, I would use the following helper function for the TListGroupsclass:
type
TListGroups = class(ComCtrls.TListGroups)
public
function FindItemByGroupID(GroupID: Integer): TListGroup;
end;
implementation
function TListGroups.FindItemByGroupID(GroupID: Integer): TListGroup;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
Result := Items[I];
if Result.GroupID = GroupID then
Exit;
end;
Result := nil;
end;
LVGroupCompare :
function LVGroupCompare(Group1_ID, Group2_ID: Integer;
pvData: Pointer): Integer; stdcall;
var
Item1: TListGroup;
Item2: TListGroup;
Groups: TListGroups;
begin
Result := 0;
Groups := TListGroups(pvData);
Item1 := Groups.FindItemByGroupID(Group1_ID);
Item2 := Groups.FindItemByGroupID(Group2_ID);
if Assigned(Item1) and Assigned(Item2) then
Result := CompareText(Item1.Header, Item2.Header);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Item: TListItem;
Group: TListGroup;
begin
Group := ListView1.Groups.Add;
Group.Header := 'AGroup';
Item := ListView1.Items.Add;
Item.Caption := 'Item X';
Item.GroupID := Group.ID;
ListView_SortGroups(ListView1.Handle, LVGroupCompare, ListView1.Groups);
end;