ListBox列表项的排序,

就是调用ListBox.Prop.Items.Sort(Compare: TListSortCompare);方法,

TListSortCompare = function (Item1, Item2: Pointer): Integer;

 

先准备一个界面,

顶部一个Panel,上面三个按钮,下面放个ListBox,如下图所示:

点击名称按钮表示按名称排序(名称保存在Item.Caption属性)

点击日期按钮表示按日期排序(日期保存在Item.Detail属性)

点击大小按钮表示按大小排序(大小保存在Item.Detail属性)

ListBox添加如下四个列表项:

 

接下来我们要实现点击名称按钮排序,

先定义一个排序方法,

方法的类型必须为TListSortCompare = function (Item1, Item2: Pointer): Integer;

如下图所示:

//按名称升序排序方法

function ListCompareByNameAsc(Item1, Item2: Pointer): Integer;

begin

  Result:=0;

  if LowerCase(TSkinListBoxItem(Item1).Caption)

      >LowerCase(TSkinListBoxItem(Item2).Caption) then

  begin

    Result:=1;

  end

  else if LowerCase(TSkinListBoxItem(Item1).Caption)

          <LowerCase(TSkinListBoxItem(Item2).Caption) then

  begin

    Result:=-1;

  end;

end;

 

然后我们写名称按钮的OnClick事件:

procedure TFrameListBox_SortItems.btnSortByNameClick(Sender: TObject);

begin

  //按名称排序

  Self.lbFileList.Properties.Items.Sort(ListCompareByNameAsc);

end;

 

运行,效果如下,5132:

点击名称按钮,1235,看,按升序排列了: