GetStrValue在自定义属性编辑器上返回空字符串

时间:2017-07-11 09:01:27

标签: delphi delphi-10.1-berlin propertyeditor property-editor

我想为自定义组件编写自定义属性编辑器。我有一个如下所示的组件声明:

type
   TEJsonQuery = class(TComponent)
   private
      FSql: TStrings;

      procedure SetSQL(const Value: TStrings);
      { Private declarations }
   protected
      { Protected declarations }
   public
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;
      { Public declarations }
   published
      property SQL: TStrings read FSql write SetSQL;
      { Published declarations }
   end;

constructor TEJsonQuery.Create;
begin
   inherited Create(AOwner);
   FSql := TStringList.Create;
end;

procedure TEJsonQuery.SetSQL(const Value: TStrings);
begin
   if SQL.Text <> Value.Text then
   begin
      //Close;
      SQL.BeginUpdate;
      try
         SQL.Assign(Value);
      finally
         SQL.EndUpdate;
      end;
   end;
end;

destructor TEJsonQuery.Destroy;
begin
   inherited Destroy;
   FSql.Free;
end;

以及如下所示的属性编辑器声明:

type
   TQuerySQLProperty = class(TStringProperty)
   public
      function GetAttributes: TPropertyAttributes; override;
      procedure Edit; override;
   end;

   Tfrm_JsonQuerySQL = class(TForm)
      btn_JsonQuerySQL: TButton;
      mem_SQL: TMemo;
    btn_OK: TButton;
    btn_Cancel: TButton;
   private
      { Private declarations }
   public
      { Public declarations }
   end;

var
   frm_JsonQuerySQL: Tfrm_JsonQuerySQL;

procedure Register;

implementation

{$R *.dfm}

procedure Register;
begin
   RegisterComponents('MyComponents', [TEJsonQuery]);
   RegisterPropertyEditor(TypeInfo(TStrings), TEJsonQuery, 'SQL', TQuerySQLProperty);
end;

procedure TQuerySqlProperty.Edit;
begin
   frm_Ekol_JsonQuerySQL := Tfrm_Ekol_JsonQuerySQL.Create(Application);
   try
      Assert(False, '"' + GetStrValue + '"');
      frm_Ekol_JsonQuerySQL.mem_SQL.Lines.Text := GetStrValue;
      // show the dialog box
      if frm_Ekol_JsonQuerySQL.ShowModal = mrOK then
      begin
         SetStrValue(frm_Ekol_JsonQuerySQL.mem_SQL.Lines.Text);
      end;
   finally
      frm_Ekol_JsonQuerySQL.Free;
   end;
end;

function TQuerySQLProperty.GetAttributes: TPropertyAttributes;
begin
   // editor, sorted list, multiple selection
   // Result := [paDialog, paMultiSelect, paValueList, paSortList];
   Result := [paDialog];
end;

如果Assert(False, '"' + GetStrValue + '"');被注释为空备忘录,则会打开属性编辑器,因为GetStrValue返回空字符串。

1 个答案:

答案 0 :(得分:3)

SQL属性是TStrings属性,而不是字符串属性,GetStrValue仅适用于字符串属性,如果选择了多个组件,则返回GetComponent(0)的值。 GetStrValue是一个虚拟属性,因此您可以实现自己的。

以下是我的想法:

type
  TQuerySqlProperty = ...
  public
    function GetStrValue : string; override;
    ...
  end;
  ...

function TQuerySqlProperty.GetStrValue : string;
begin
  if GetComponent(0) is TEJsonQuery then
  begin
    Result := (GetComponent(0) as TEJsonQuery ).SQL.Text;
  end
  else
  begin
    Result := inherited;
  end;
end;