宣告屬性時可指定預設值。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 指令;首次宣告無預設值則無需指定。
物件檢視器提供內建編輯器,亦支援自訂編輯器。開發步驟五階段:
GetValue/SetValue)Edit 方法,通常彈出對話框)GetAttributes)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/ATColorProperty 同時支援輸入、下拉選單與對話框,故回傳 [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;