Mega Code Archive

 
Categories / Delphi / Examples
 

How to override a property

Title: How to override a property Question: Trigger-methods of properties are sometimes declared in the private-section of a class... there is a simply trick how to override these properties. Answer: An example to show this is the TEdit class. Lets say we want to make the background-color of this control gray when ReadOnly is set to true. The problem is that SetReadOnly is private.. so can not be overriden. The solution is to simply REPLACE the SetReadOnly function and call inherited with the ReadOnly-property of the parent-class: inherited ReadOnly:= Value; All other code (Loaded, Create) is just to get the correct default-color that was set by the developer at design-time. type TMyEdit = class(TEdit) private FDesignColor: TColor; FReadOnly: boolean; procedure SetReadOnly(Value: boolean); procedure SetColor; protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; published property ReadOnly: boolean read FReadOnly write SetReadOnly; end; implementation constructor TMyEdit.Create(AOwner: TComponent); begin inherited; FDesignColor:= clWindow; end; procedure TMyEdit.Loaded; begin inherited; FDesignColor:= Color; end; procedure TMyEdit.SetColor; begin if ReadOnly then Color:= clBtnFace else Color:= FDesignColor; end; procedure TMyEdit.SetReadOnly(Value: boolean); begin FReadOnly:= Value; inherited ReadOnly:= Value; SetColor; end;