如何垂直居中TListBox项目?

时间:2017-05-10 12:42:23

标签: delphi listbox centering tlistbox

所以我想垂直居中TListBox(不是TListView)项目。

我可以使用TopIndex属性,但我该怎么做呢。

如果项目较少而滚动条没有出现,则不需要居中,只选择默认项目就可以了。

这样的事情:

Vertically Centered TListBox

1 个答案:

答案 0 :(得分:5)

enter image description here

//IF YOU WANT TO SELECT THE CENTER ITEM 
procedure TForm2.Center;
  var VisibleItems : Integer;
begin
  VisibleItems := ListBox1.ClientHeight div  ListBox1.ItemHeight;
  ListBox1.TopIndex := Trunc((ListBox1.Items.Count / 2) - (VisibleItems / 2));
  if ListBox1.Items.Count > VisibleItems then
    ListBox1.Selected[ListBox1.TopIndex + (VisibleItems div 2)] := True
  else
    ListBox1.Selected[ListBox1.Items.Count div 2] := True;
end;



//IF YOU WANT TO CENTER A ITEM
procedure TForm2.Center(Index : Integer);
  var VisibleItems : Integer;
begin
  VisibleItems := ListBox1.ClientHeight div ListBox1.ItemHeight;
  if Index > VisibleItems then
    ListBox1.TopIndex :=  Index - (VisibleItems div 2);
end;