Skip to content

Instantly share code, notes, and snippets.

@UweRaabe
Created June 10, 2024 22:28
Show Gist options
  • Save UweRaabe/f701ff66dcc23b03dd8a9294fdf148ba to your computer and use it in GitHub Desktop.
Save UweRaabe/f701ff66dcc23b03dd8a9294fdf148ba to your computer and use it in GitHub Desktop.
TUpperCaseString auto-converts assigned string to uppercase (with property editor and example component)
unit Test.UpperCaseString.Design;
interface
procedure Register;
implementation
uses
System.Classes,
Test.UpperCaseString;
procedure Register;
begin
RegisterComponents('Samples', [TTestUpperCaseString]);
end;
end.
unit Test.UpperCaseString;
interface
uses
System.Classes,
UpperCaseString.Types;
type
TTestUpperCaseString = class(TComponent)
private
FCaptionUpper: TUpperCaseString;
published
property CaptionUpper: TUpperCaseString read FCaptionUpper write FCaptionUpper;
end;
implementation
end.
unit UpperCaseString.Design;
interface
uses
DesignEditors;
type
TUpperCaseStringEditor = class(TPropertyEditor)
public
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
procedure Register;
implementation
uses
System.Rtti,
DesignIntf,
UpperCaseString.Types;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TUpperCaseString), nil, '', TUpperCaseStringEditor);
end;
function TUpperCaseStringEditor.GetValue: string;
begin
var context := TRttiContext.Create;
var instance := GetComponent(0);
var typ := context.GetType(instance.ClassType);
var prop := typ.GetProperty(GetPropInfo.Name);
var value := prop.GetValue(instance);
Result := value.AsType<TUpperCaseString>;
end;
procedure TUpperCaseStringEditor.SetValue(const Value: string);
begin
var context := TRttiContext.Create;
var instance := GetComponent(0);
var typ := context.GetType(instance.ClassType);
var prop := typ.GetProperty(GetPropInfo.Name);
prop.SetValue(instance, TValue.From<TUpperCaseString>(Value));
end;
end.
unit UpperCaseString.Types;
interface
type
TUpperCaseString = record
private
FValue: string;
public
class operator Implicit(A: TUpperCaseString): string; overload;
class operator Implicit(A: string): TUpperCaseString; overload;
end;
implementation
uses
System.SysUtils;
class operator TUpperCaseString.Implicit(A: TUpperCaseString): string;
begin
Result := A.FValue;
end;
class operator TUpperCaseString.Implicit(A: string): TUpperCaseString;
begin
Result.FValue := A.ToUpper;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment