如何为TFileListBox实现OnSelectionChanged事件?

WeG*_*ars 3 delphi

我想为TFileListBox创建一个新事件.我想知道用户何时选择其他项目.

实现它的最佳方法是在用户按下鼠标按钮时调用该事件,如下所示:

procedure TMyFileList.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
VAR PrevItem: Integer;
begin
 PrevItem:= ItemIndex; <---------- Problem here
 inherited;
 if (Count> 0)
 AND ( PrevItem<> ItemIndex )                                                  
 AND Assigned(FOnSelChaged)
 then FOnSelChaged(Self, PrevItem);
end;
Run Code Online (Sandbox Code Playgroud)

所以,假设已经选择了第一项(ItemIndex = 0).一旦我按下鼠标按钮选择第二个项目,我就进入MouseDown程序.但是这里的ItemIndex已经是1而不是0.为什么?

Dav*_*nan 6

TFileListBox维护一个名为的受保护字段FLastSel,这正是您所需要的.您的代码的另一个大问题是您假设只能通过鼠标更改选择.不要忘记键盘或程序修改.您正在寻找名为的虚拟方法Change.

所以,把它们放在一起,就可以做到这一点:

TMyFileListBox = class(TFileListBox)
protected
  procedure Change; override;
.... 

procedure TMyFileListBox.Change;
begin
  if (Count>0) and (FLastSel<>ItemIndex) and Assigned(FOnSelChanged) then        
    FOnSelChanged(Self, FLastSel, ItemIndex);
  inherited;
end;
Run Code Online (Sandbox Code Playgroud)

我们必须FLastSel在调用继承Change方法之前使用它,因为它FLastSel被改变为等于当前选择.

procedure TFileListBox.Change;
begin
  FLastSel := ItemIndex;
  .... continues
Run Code Online (Sandbox Code Playgroud)

  • 而古老的,失落的德尔福世界1. :) (2认同)