2010-01-15 78 views
6

我使用德尔福5,我们有一个方法可以动态地创建基于数据库表的内容某些控件的属性(我们创建大多TButtons)和那些被点击时采取行动。这使我们可以将简单的控件添加到表单中,而无需重新编译应用程序。动态访问德尔福组件

我想知道是否有可能基于字符串中包含的,所以我们可以设置更多选项属性名称设置组件的属性。

伪代码:

Comp := TButton.Create(Self); 

// Something like this: 
Comp.GetProperty('Left').AsInteger := 100; 
// Or this: 
Comp.SetProperty('Left', 100); 

这是可能的呢?

+1

要知道,在你的配置畸形的内容可能会引领你进入有趣的故障模式。 (在那里,完成了。) – 2010-01-15 14:16:46

回答

11

你必须使用Delphi的运行时类型信息功能来做到这一点:

该博客介绍,正是你正在尝试做的:Run-Time Type Information In Delphi - Can It Do Anything For You?

基本上你必须让物业信息,使用GetPropInfo然后使用SetOrdProp来设置该值。

var 
    PropInfo: PPropInfo; 
begin 
    PropInfo := GetPropInfo(Comp.ClassInfo, 'Left'); 
    if Assigned(PropInfo) then 
    SetOrdProp(Comp, PropInfo, 100); 
end; 

这不像您的伪代码那样简洁,但它仍然可以完成这项工作。其他东西也变得更复杂,比如数组属性。

+0

辉煌,我现在解析一个字符串,实例化控件,并动态设置属性! – Drarok 2010-01-15 13:38:15

+0

这也许会让你感兴趣:http://www.remobjects.com/ps.aspx – 2010-01-15 13:55:53

9

从我工作的单位之一(Delphi 7中虽然)

var 
    c : TComponent; 

    for i := 0 to pgcProjectEdits.Pages[iPage].ControlCount - 1 do 
    begin 
    c := pgcProjectEdits.Pages[iPage].Controls[i]; 
    if c is TWinControl 
    then begin 
     if IsPublishedProp(c,'color') 
     then 
      SetPropValue(c,'color',clr); 
     if IsPublishedProp(c,'readonly')       
     then              
      SetPropValue(c,'readonly', bReadOnly); 
     ...    
    end; 
    ... 

你必须包括在uses语句TypInfo。 不知道,如果这个工程德尔福5.下

+0

啊,IsPublishedProp()比上面好得多,我在我的代码中使用了两者的组合。非常感谢。 – Drarok 2010-01-15 13:39:52