【问题标题】:How to change the group order in a TListGroups?如何更改 TListGroups 中的组顺序?
【发布时间】:2018-05-07 17:24:58
【问题描述】:

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

【问题讨论】:

    标签: listview delphi delphi-2009


    【解决方案1】:

    您可以通过更改组项的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;
    

    【讨论】:

    • 当然,您可能想通过提取GetGroupFromGroupID 函数来重构它。
    • 但是我在哪里可以找到那个函数呢?
    • “提取重构”是指你自己编写函数。
    【解决方案2】:

    是的。通过更改组项的Index

    【讨论】:

    • 值得补充的是,MS 为此目的制作了 API(LVM_MOVEGROUP 消息或ListView_MoveGroup 宏)。但他们没有实施。
    • 没关系。更改索引效果很好。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多