2011-08-19 93 views
0

我正在使用Delphi Prism for .NET。我需要從另一個winform方法中調用我的mainform類中的公共方法。所以,最近我瞭解了靜態,我在程序中使用了它。靜態或類的winform工程很好,但使一個方法靜態或類似乎沒有相同的工作。Delphi Prism中的靜態或類方法

我有一個叫我MainForm類updateButtons方法。它根據用戶的操作更新mainform上的所有按鈕和控件。該方法需要從另一個winform方法中調用。所以,我將該UpdateButtons方法變爲靜態或類。雖然現在我看到要調用的方法,但編譯器不喜歡。它不斷提出以下錯誤,「無法調用實例成員(任何控件)沒有實例引用。」

你怎麼能做出一個方法從WinForm的類或靜態的,仍然可以訪問控制?

主要類的靜態或類方法:updatebutton的

MainForm = partial class(System.Windows.Forms.Form) 
    private 
    protected 
    method Dispose(disposing: Boolean); override; 
    public 
    class method updateButtons; 
    end; 

定義:

class method MainForm.updateButtons; 
begin  
     if SecurityEnabled then 
       LoginBtn.Enabled := true  //All the lines where I call Buttons raise the error exception that I mentioned above. 
     else 
     begin 
       UnitBtn.Enabled := true; 
       SignalBtn.Enabled := true; 
       AlarmBtn.Enabled := true; 
       MakerBtn.Enabled := true; 
       TrendBtn.Enabled := true; 
       DxCommBtn.Enabled := (Scanning = false); 
       TxBtn.Enabled := true; 
       ControlBtn.Enabled := true; 
       PIDBtn.Enabled := true; 
       SystemBtn.Enabled := true; 
       WinListBox.Enabled := true; 
       WinBtn.Enabled := true; 
       ShutdownBtn.Enabled := true; 
       OptionBtn.Enabled := true; 
       LoginBtn.Enabled:=false; 
     end; 
    end; 

回答

0

因爲我想執行的方法是從MainForm的窗口形式與從一個按鈕事件中開槍,我決定從MainForm的,而不是從其他WinForm的調用這個方法從按鈕的Click事件中。這具有相同的最終結果。另外,它更簡單。

//This is just a sample code 
MainForm = class(system.windows.forms.form) 
private 
    method ScanBtn_Click(sender: System.Object; e: System.EventArgs); 
protected 
public 
    Method UpdateButtons; 
end; 

Method Mainform.UpdateButtons; 
begin 
    Button1.enabled:=true; 
    Button1.text:='Start Scanning'; 
end; 

method MainForm.ScanBtn_Click(sender: System.Object; e: System.EventArgs); 
begin 
    if not Scanning then 
     stopthread:=true; 

    dxCommWin.Scan(not Scanning); 
    UnitWin.UpdateMenu; 
    UpdateButtons; <-------I call it here instead of from dxCommWin.Scan Method. 
end; 
+1

實際上,在這種情況下,如果你想從dxCommWin.Scan中調用它,你可以簡單地將引用傳遞給MainForm(self)作爲方法的第二個參數:''dxCommWin.Scan(不掃描,自我)在這種情況下,該方法的簽名看起來像'method dxCommWin.Scan(scanning:boolean; form:MainForm);'並且您可以從該方法內訪問表單。那就是我的意思是「檢索對錶單的引用」。 –

+0

是的。我計劃實現一個類似的代碼,但我想到了我的解決方案,似乎更合適,因爲這就是我想要做的 - 在調用dxCommWin.Scan之後立即執行該方法。謝謝,塞巴斯蒂安。 – ThN

1

這不能在你想要的工作方式工作。

的類(或靜態)方法是被靜態調用的類,而不是在一個特定的對象實例被調用。

您可以實例化幾次相同的表單類。然後你有幾個表單的對象實例,它們可以同時打開或隱藏。

現在,當你調用靜態方法,這些幾種形式,它們應該更新?編譯器無法識別,也不能訪問屬於該對象實例的字段或屬性。

對於這個工作,你必須使該方法的對象(非類或靜態)的正常方法,你需要檢索的具體形式對象實例的引用,並調用它。

+0

@ Sebastian,你說得對。由於它是一種方法,並將其變爲靜態類,所以它本身需要實例化。事實上,它甚至不認可來自MainForm的任何控制。你的解決方案看起來很簡單,但需要一些操作 – ThN

+0

@ Sebastian你的解釋確實澄清了我的誤解,並幫助我達成了一個解決方案,儘管我沒有接受你的答案。所以,我投了你的答案。謝謝。 – ThN

相關問題