2010-01-15 80 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