Altering ITEMINDEX of TComboBox does not trigger it's OnChange event

心不动则不痛 提交于 2020-01-15 03:13:11

问题


When programmatically changing the value of ItemIndex of a TComboBox component in Delphi, one would expect for the corresponding OnChange event to get triggered.

Afterall, the visible value of the ComboBox get's changed as a result. Strangely it does not. Same behavior in Delphi6, Delphi 2010 and Delphi XE7.

Is there any reason behind this behavior or it's just a pending bug?


回答1:


From documentation:

Occurs when the user changes the text displayed in the edit region.

Write an OnChange event handler to take specific action immediately after the user edits the text in the edit region or selects an item from the list. The Text property gives the new value in the edit region.

Note: OnChange only occurs in response to user actions. Changing the Text property programmatically does not trigger an OnChange event.

Since there is no editing done, this means that programmatically changing the ItemIndex does not trigger the OnChange event.




回答2:


As others have answered, it is as designed. You can, however, achieve the functionality you are missing by overriding the SetItemIndex() procedure as follows:

type
  TComboBox = class(Vcl.StdCtrls.TComboBox)
    procedure SetItemIndex(const Value: Integer); override;
  end;

  TForm3 = class(TForm)
    ...


implementation

procedure TComboBox.SetItemIndex(const Value: Integer);
begin
  inherited;
  if Assigned(OnSelect) then
    OnSelect(self);
end;

As you see I activate the OnSelect event instead of OnChange, because OnSelect is the one fired when you select an item from the dropdown list. You can, if you like, just as well use the OnChange event instead.




回答3:


That is designed behavior. OnChange event is triggered only by user actions and not programatically.

OnChange Event

Occurs when the user changes the text displayed in the edit region. Write an OnChange event handler to take specific action immediately after the user edits the text in the edit region or selects an item from the list. The Text property gives the new value in the edit region.

Note: OnChange only occurs in response to user actions. Changing the Text property programmatically does not trigger an OnChange event.



来源:https://stackoverflow.com/questions/37586597/altering-itemindex-of-tcombobox-does-not-trigger-its-onchange-event

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