|
Adding custom properties
TComponentInspector supports the custom properties, so you can add any property to any component type easily. The new property can be registered with the RegisterCustomProperty procedure from the PropList unit.
procedure RegisterCustomProperty(
AInstanceType: TClass; // component type
APropName: string; // new property name
APropType: PTypeInfo; // property type (use TypeInfo)
ADescendants: Boolean; // True if you want to add new property
// to all AInstanceType's descendants
AGetProc: TGetPropertyValue; // get value function
ASetProc: TSetPropertyValue); // set value procedure
TGetPropertyValue and TSetPropertyValue are defined as
TGetPropertyValue = function( // value must be returned as string
AInstance: TPersistent; // edited component
Prop: TProperty): string; // edited property
TSetPropertyValue = procedure(
AInstance: TPersistent; // edited component
Prop: TProperty; // edited property
Value: string); // value that must be set
Let's create the new ColorScheme property for the form. It's as simple as 1-2!
[1]
Let's create the routines for setting and getting the property value using the new special TColorScheme type
type
TColorScheme = (Normal,Flame,Grass,Sun,Moon);
...
function GetPropValue(AInstance: TPersistent; Prop: TProperty): string;
begin
with Prop do
case (AInstance as TForm).Color of
clRed: Result:=Names[Integer(Flame)];
clGreen: Result:=Names[Integer(Grass)];
clYellow: Result:=Names[Integer(Sun)];
clNavy: Result:=Names[Integer(Moon)];
else Result:=Names[Integer(Normal)];
end;
end;
procedure SetPropValue(AInstance: TPersistent; Prop: TProperty;
Value: string);
begin
with (AInstance as TForm) do
case TColorScheme(Prop.Values[Value]) of
Normal:
begin
Color:=clBtnFace;
Font.Color:=clBlack;
end;
Flame:
begin
Color:=clRed;
Font.Color:=clYellow;
end;
Grass:
begin
Color:=clGreen;
Font.Color:=clLime;
end;
Sun:
begin
Color:=clYellow;
Font.Color:=clBlack;
end;
Moon:
begin
Color:=clNavy;
Font.Color:=clAqua;
end;
end;
end;
[2]
Let's register the new property using RegisterCustomProperty procedure
procedure TMainForm.FormShow(Sender: TObject);
begin
// registering the new property
RegisterCustomProperty(
TForm,
'ColorScheme',
TypeInfo(TColorScheme),
True,
GetPropValue,
SetPropValue);
// refresh inspector to see the new property
ComponentInspector.RefreshList;
end;
We can hide the standard Color property in the from and in the form font with OnFilter event and allow the user to change the colors only by the new ColorScheme property
procedure TMainForm.ComponentInspectorFilter(Sender: TObject;
Prop: TProperty; var Result: Boolean);
begin
Result:=Result and (Prop.PropType<>TypeInfo(TColor));
end;
To unregister the custom property just call UnregisterCustomProperty procedure or UnregisterCustomProperties if you want to unregister all custom properties.
|