首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 元件屬性開發:預設值、屬性編輯器建立與註冊實戰

     編輯:Delphi

19.2.2.1 建立屬性(續)

⑸ 預設屬性值

宣告屬性時可指定預設值。Delphi 依據預設值決定是否將屬性寫入 DFM 檔案:若屬性值等於預設值則省略儲存。語法:property PropName: Type read ... write ... default Value;。建構子中必須將欄位初始化為相同預設值。

type
  TSampleComponent = class(TComponent)
  private
    FIsTrue: Boolean;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property IsTrue: Boolean read FIsTrue write FIsTrue default True;
  end;

constructor TSampleComponent.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FIsTrue := True; { 設定預設值 }
end;

重新宣告屬性時,若祖先有預設值而欲移除,使用 nodefault 指令;首次宣告無預設值則無需指定。

5. 編寫屬性編輯器

物件檢視器提供內建編輯器,亦支援自訂編輯器。開發步驟五階段:

  1. 繼承屬性編輯器基類
  2. 實作文字編輯(GetValue/SetValue)
  3. 實作整體編輯(Edit 方法,通常彈出對話框)
  4. 描述編輯器特性(GetAttributes)
  5. 註冊編輯器

⑴ 繼承屬性編輯器對象

DsgnIntf 單元定義多種基類(TOrdinalProperty、TStringProperty、TColorProperty 等),對應不同資料型別。選擇最貼近的基類繼承可減少工作量。

⑵ 文字編輯實作

覆寫 GetValue 回傳字串表示,SetValue 解析字串並寫入。基類提供型別專用讀寫方法(GetOrdValue/SetOrdValue、GetStrValue/SetStrValue 等)。TIntegerProperty 範例演示範圍檢查與轉換。

⑶ 整體編輯對話框

覆寫 Edit 方法,建立對話框(如 TColorDialog),以 GetOrdValue 取得現值,Execute 後以 SetOrdValue 寫回,最後釋放對話框。

⑷ 描述編輯器特性

覆寫 GetAttributes 回傳 TPropertyAttributes 集合:

  • paValueList:提供下拉選單(需實作 GetValues)
  • paSubProperties:可展開子屬性(需實作 GetProperties)
  • paDialog:支援彈出對話框(需實作 Edit)
  • paMultiSelect:多選元件時顯示 N/A

TColorProperty 同時支援輸入、下拉選單與對話框,故回傳 [paMultiSelect, paDialog, paValueList]。

⑸ 註冊屬性編輯器

呼叫 RegisterPropertyEditor,四參數:屬性型別資訊(TypeInfo)、適用元件類別(nil 表所有)、屬性名稱(僅前參數非 nil 時有效)、編輯器類別。標準註冊範例:

procedure Register;
begin
  RegisterPropertyEditor(TypeInfo(TComponent), nil, '', TComponentProperty);
  RegisterPropertyEditor(TypeInfo(TComponentName), TComponent, 'Name', TComponentNameProperty);
  RegisterPropertyEditor(TypeInfo(TMenuItem), TMenu, '', TMenuItemProperty);
end;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved