說明:展示 ListView 視其每一行 Item 的 Detail 字串長度自動調整高度(可每行高度不同)。
適用:Delphi XE7
源碼下載:[原創]ListView_自動計算行高(by龜山阿卍).zip
procedure TForm1.Button1Click(Sender: TObject); const DetailStr: array[0..2] of String = ('1234567890123456789012345678901234567890123456789012345678901234567890' ,'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' ,'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ' ); var i, r: Integer; Item1: TListViewItem; begin for i:=0 to 100 do begin Item1 := ListView1.Items.Add; r := Random(3); Item1.Detail := DetailStr[r].Substring(0, Random(DetailStr[r].Length)); Item1.Text := i.ToString; end; end; procedure TForm1.ListView1UpdateObjects(const Sender: TObject; const AItem: TListViewItem); var R: TRectF; begin if (AItem.Objects.DetailObject <> nil) and (AItem.Objects.DetailObject.Text <> '') then begin // 計算文字顯示的區域 R := RectF(0, 0, AItem.Objects.DetailObject.Width, 10000); ListView1.Canvas.MeasureText(R, AItem.Objects.DetailObject.Text, AItem.Objects.DetailObject.WordWrap, [], TTextAlign.Leading, TTextAlign.Leading); // 設定高度 AItem.Height := Trunc(R.Height); end; end;