Delphi TListBox OnClick / OnChange?

那年仲夏 提交于 2019-12-05 23:07:29

问题


Is there a trick to getting "OnChange" type of functionality with a TListBox? I can subclass the component and add a property, etc then only carry out OnClick code if the Index changes... I can also hack it with a form level variable to store the current index but just wondering if I'm overlooking the obvious before I go one way or the other.


回答1:


There seems to be no way other than implementing this by yourself. What you need is to remember the currently selected item and whenever the ItemIndex property is changed from code or whenever the control receives the LBN_SELCHANGE notification (which currently fires the OnClick event), you will compare the item index you stored with item index which is currently selected and if they differ, fire your own OnChange event. In code of an interposed class it could be:

type
  TListBox = class(StdCtrls.TListBox)
  private
    FItemIndex: Integer;
    FOnChange: TNotifyEvent;
    procedure CNCommand(var AMessage: TWMCommand); message CN_COMMAND;
  protected
    procedure Change; virtual;
    procedure SetItemIndex(const Value: Integer); override;
  published
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

implementation

{ TListBox }

procedure TListBox.Change;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

procedure TListBox.CNCommand(var AMessage: TWMCommand);
begin
  inherited;
  if (AMessage.NotifyCode = LBN_SELCHANGE) and (FItemIndex <> ItemIndex) then
  begin
    FItemIndex := ItemIndex;
    Change;
  end;
end;

procedure TListBox.SetItemIndex(const Value: Integer);
begin
  inherited;
  if FItemIndex <> ItemIndex then
  begin
    FItemIndex := ItemIndex;
    Change;
  end;
end;



回答2:


with the OnClick event is just like this...you need to store the last value to compare it.

if ListBox1.Items[ListBox1.ItemIndex]<> Edit1.Text then
    Edit1.Text := ListBox1.Items[ListBox1.ItemIndex];


来源:https://stackoverflow.com/questions/20889016/delphi-tlistbox-onclick-onchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!