如何更改 TListGroups 中的组顺序?

How to change the group order in a TListGroups?

我有一个 TListViewvsReport 样式,其中组可见。组按创建顺序显示。但我想制作两个按钮(向上和向下)并将所选组移动到另一个位置(在运行时)。可能吗?

是的。通过更改组项的 Index.

您可以通过更改组项目的 Index 属性 来实现。下面的代码演示了用法:

procedure TForm1.btnMoveUpClick(Sender: TObject);
var
  itm: TListItem;
  i: Integer;
begin
  itm := ListView1.Selected;
  if Assigned(itm) then
    for i := 0 to ListView1.Groups.Count - 1 do
      if ListView1.Groups[i].GroupID = itm.GroupID then
      begin
        if ListView1.Groups[i].Index > 0 then
          ListView1.Groups[i].Index := ListView1.Groups[i].Index - 1;
        break;
      end;
end;

procedure TForm1.btnMoveDownClick(Sender: TObject);
var
  itm: TListItem;
  i: Integer;
begin
  itm := ListView1.Selected;
  if Assigned(itm) then
    for i := 0 to ListView1.Groups.Count - 1 do
      if ListView1.Groups[i].GroupID = itm.GroupID then
      begin
        if ListView1.Groups[i].Index < ListView1.Groups.Count - 1 then
          ListView1.Groups[i].Index := ListView1.Groups[i].Index + 1;
        break;
      end;
end;

脚注:当然可以(应该)这样重构:

function GetGroupFromGroupID(AListView: TListView; AGroupID: integer): TListGroup;
var
  i: Integer;
begin
  for i := 0 to AListView.Groups.Count - 1 do
    if AListView.Groups[i].GroupID = AGroupID then
      Exit(AListView.Groups[i]);
  result := nil;
end;

procedure TForm1.btnMoveUpClick(Sender: TObject);
var
  itm: TListItem;
  grp: TListGroup;
begin
  itm := ListView1.Selected;
  if Assigned(itm) then
  begin
    grp := GetGroupFromGroupID(ListView1, itm.GroupID);
    if Assigned(grp) and (grp.Index > 0) then
      grp.Index := grp.Index - 1;
  end;
end;

procedure TForm1.btnMoveDownClick(Sender: TObject);
var
  itm: TListItem;
  grp: TListGroup;
begin
  itm := ListView1.Selected;
  if Assigned(itm) then
  begin
    grp := GetGroupFromGroupID(ListView1, itm.GroupID);
    if Assigned(grp) and (grp.Index < ListView1.Groups.Count - 1) then
      grp.Index := grp.Index + 1;
  end;
end;