【发布时间】:2011-01-01 03:04:42
【问题描述】:
我有一个用于编辑属性的属性编辑器(TPropertyEditor 的后代)。
当需要编辑我的属性时,我如何知道我正在编辑的对象的哪个属性?如果我要编辑一个属性,我必须知道我正在编辑什么属性。
我一直在摸索,筛选 Delphi 帮助、在线帮助以及 TPropertyEditor 和后代源代码,但找不到答案。
我希望是这样的:
TPropertyEditor = class(...)
public
procedure Initialize(TheObject: TObject; ThePropertyName: string);
end;
据我所知,我的属性编辑器已创建,我将被告知“编辑”,我只需要猜测他们希望我编辑的属性。
来自帮助:
整体编辑属性
您可以选择提供一个对话框 用户可以在其中直观地看到的框 编辑属性。最常见的用途 of 属性编辑器用于属性 它们本身就是类。一个 例如 Font 属性,例如 用户可以打开一个字体对话框 框选择所有属性 字体。
提供一个 整体属性编辑器对话框, 覆盖属性编辑器类的 编辑方法。
Edit 方法使用相同的 写作中使用的 Get 和 Set 方法 GetValue 和 SetValue 方法。在 事实上,Edit 方法同时调用 Get 方法和 Set 方法。因为 编辑器是特定于类型的,有 通常不需要转换 属性值到字符串。编辑 通常处理值“as 已取回。”
当用户点击“...”按钮时 在属性旁边或双击 值列,对象检查器 调用属性编辑器的 Edit 方法。
在您实施 Edit 方法,请按以下步骤操作:
- 构建您正在使用的编辑器 为财产。
- 读取当前 值并将其分配给属性 使用 Get 方法。
- 当用户 选择一个新值,分配该值 使用 Set 方法到属性。
- 销毁编辑器。
回答
它被隐藏起来,没有记录,但我发现了如何。我正在编辑的属性:
TheCurrentValue := TMyPropertyThing(Pointer(GetOrdValue));
现在我有了值,我可以编辑它。如果我想用其他对象替换该属性:
SetOrdValue(Longint(TheNewValue));
完整代码:
创建一个继承自TClassProperty的属性编辑器:
TMyPropertyEditor = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
首先是家务,告诉Delphi的对象检查器我的属性编辑器会显示一个对话框,这会让属性旁边出现一个“...”:
function TMyPropertyEditor.GetAttributes: TPropertyAttributes;
begin
//We show a dialog, make Object Inspector show "..."
Result := [paDialog];
end;
接下来是实际工作。当用户单击“...”按钮时,对象检查器会调用我的 Edit 方法。我缺少的技巧是我调用了我的 GetOrdValue 方法。即使我的属性不是 ordinal,您仍然可以使用它,并且只需将生成的东西转换为对象:
procedure TMyPropertyEditor.Edit;
var
OldThing: TMyPersistentThing;
NewThing: TMyPersistentThing;
begin
//Call the property's getter, and return the "object" i'm editing:
OldThing:= TMyPersistentThing(Pointer(GetOrdValue));
//now that i have the thing i'm editing, do stuff to "edit" it
DoSomeEditing(OldThing);
//i don't have to, but if i want to replace the property with a new object
//i can call the setter:
NewThing := SomeVariant(OldThing);
SetOrdValue(Longint(NewThing));
end;
【问题讨论】:
标签: delphi propertyeditor