ListView點擊列排序

很想實現像Windows資源管理器在使用詳細資料方式查看文件時,點擊列標題自動排序的功能。看了Delphi6的幫助,基本的排序功能是實現了,但不能顯示錶示升/降序的“小三角”。因爲技術有限,找不出實現列標題顯示的代碼 ,也不會重寫顯示“小三角”的代碼,所以只好使用兩個特殊符號中的箭頭來表示,哪位高手能實現“小三角”的請指教指教!代碼如下:

 

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls;

const
  AscText = '↑';
  DescText = '↓';
  
type
  TForm1 = class(TForm)
    ListView1: TListView;
    procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem;
      Data: Integer; var Compare: Integer);
    procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
    procedure ListView1CustomDraw(Sender: TCustomListView;
      const ARect: TRect; var DefaultDraw: Boolean);
  private
    { Private declarations }
    ColumnToSort: Integer;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function GetSortType(S: String): Integer;
begin
  Result:= 0;
  if pos(AscText, S) > 0 then
    Result:= 1
  else if pos(DescText, S) > 0 then
    Result:= -1;
end;

procedure TForm1.ListView1Compare(Sender: TObject; Item1, Item2: TListItem;
  Data: Integer; var Compare: Integer);
var
  ix: Integer;
begin
  if GetSortType(Item1.ListView.Column[ColumnToSort].Caption) >= 0 then
  begin
    if ColumnToSort = 0 then
      Compare := CompareText(Item1.Caption,Item2.Caption)
    else begin
     ix := ColumnToSort - 1;
     Compare := CompareText(Item1.SubItems[ix],Item2.SubItems[ix]);
    end;
  end
  else begin
    if ColumnToSort = 0 then
      Compare := CompareText(Item2.Caption,Item1.Caption)
    else begin
     ix := ColumnToSort - 1;
     Compare := CompareText(Item2.SubItems[ix],Item1.SubItems[ix]);
    end;
  end;
end;

procedure TForm1.ListView1ColumnClick(Sender: TObject;
  Column: TListColumn);
var
  i: Integer;
begin
  case GetSortType(Column.Caption) of
    -1: Column.Caption:= StringReplace(column.Caption, DescText, AscText, []);
    0: Column.Caption:= Column.Caption + AscText;
    1: Column.Caption:= StringReplace(column.Caption, AscText, DescText, []);
  end;
 
  ColumnToSort := Column.Index;
  (Sender as TCustomListView).AlphaSort;
end;

procedure TForm1.ListView1CustomDraw(Sender: TCustomListView;
  const ARect: TRect; var DefaultDraw: Boolean);
var
  i: Integer;
  List: TListView;
begin
  if Sender is TListView then
  begin
    List:= (Sender as TListView);
    for i:= 0 to List.Columns.Count -1 do
    begin
      if i <> ColumnToSort then
      begin
        List.Columns[i].Caption:=
          StringReplace(List.Columns[i].Caption, AscText, '', []);
        List.Columns[i].Caption:=
          StringReplace(List.Columns[i].Caption, DescText, '', []); 
      end;
    end;
  end;
end;

end.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章