在Delphi中,TListBox是一个常用的控件,用于显示项目列表。以下是TListBox的一些常见用法:
添加项目:
使用ListBox.Items.Add
方法可以向列表框中添加项目。例如:ListBox1.Items.Add('Item 1'); ListBox1.Items.Add('Item 2');
删除项目:
使用ListBox.Items.Delete
方法可以删除指定位置的项目。例如:ListBox1.Items.Delete(0); // 删除第一个项目
清空列表:
使用ListBox.Items.Clear
方法可以清空列表框中的所有项目。例如:ListBox1.Items.Clear;
获取所选项目:
你可以通过ListBox.ItemIndex
属性获取用户当前选择的项目的索引。然后,你可以使用该索引来获取所选项目的值。例如:if ListBox1.ItemIndex <> -1 then ShowMessage('Selected item: ' + ListBox1.Items[ListBox1.ItemIndex]);
多选模式:
ListBox可以配置为允许多选。你可以通过设置ListBox.MultiSelect
为True启用多选模式。在多选模式下,可以使用ListBox.Selected[]
属性来检查或设置所选项目。例如:ListBox1.MultiSelect := True; // 设置选中项 ListBox1.Selected[0] := True; ListBox1.Selected[2] := True;
事件处理:
ListBox具有多种事件,你可以利用这些事件来响应用户操作,如点击、双击、选择等。常见的事件包括OnClick
、OnDblClick
、OnSelect
等。自定义项目样式:
你可以通过设置ListBox.Style
属性为lbOwnerDrawFixed
或lbOwnerDrawVariable
来自定义项目的外观。然后,在OnDrawItem
事件中绘制每个项目的外观。item的拖拽:
首先确保ListBox的 DragMode 属性设置为 dmAutomatic,以便启用自动拖拽模式。procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Idx: Integer; Pos: TPoint; begin Accept := False; if Sender is TListBox then with Sender as TListBox do begin Pos.X := X; Pos.y := Y; Idx := ItemAtPos(Pos, True); if (Idx > -1) and (idx <> ItemIndex) then Accept := True; end; end; procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var Idx: Integer; Pos: TPoint; begin if Sender is TListBox then begin with Sender as TListBox do begin Pos.X := X; Pos.y := Y; Idx := ItemAtPos(Pos, True); Items.Move(ItemIndex, Idx); ItemIndex := Idx; end; end; end;
item的上下移动:
procedure LbMoveItemUp(AListBox: TListBox); var CurrIndex: Integer; begin with AListBox do if ItemIndex > 0 then begin CurrIndex := ItemIndex; Items.Move(ItemIndex, (CurrIndex - 1)); ItemIndex := CurrIndex - 1; end; end; // Move an item down procedure LbMoveItemDown(AListBox: TListBox); var CurrIndex, LastIndex: Integer; begin with AListBox do begin CurrIndex := ItemIndex; LastIndex := Items.Count; if ItemIndex <> -1 then begin if CurrIndex + 1 < LastIndex then begin Items.Move(ItemIndex, (CurrIndex + 1)); ItemIndex := CurrIndex + 1; end; end; end; end; procedure TForm1.Button6Click(Sender: TObject); begin LbMoveItemUp(ListBox1); end; procedure TForm1.Button7Click(Sender: TObject); begin LbMoveItemDown(ListBox1); end;