2012-10-15 28 views
1

我需要做一些控制靜態的,例如:是否允許在窗體設計器生成的代碼(* .Designer.cs文件)中更改代碼以使某些控件成爲靜態的?

string myInfo = CourseWork.Form1.infoBox.Text; 

但是當我使用可視化設計,視覺工作室改變了我的代碼:

private static System.Windows.Forms.TextBox infoBox; 
infoBox = new System.Windows.Forms.TextBox(); 

,所以我將能夠在其他類使用於:

private System.Windows.Forms.TextBox infoBox; // it removes static 
this.infoBox = new System.Windows.Forms.TextBox(); // and add .this 

然後我有一個錯誤:

An object reference is required for the non-static field, 
method, or property 'CourseWork.Form1.infobox' 

可以避免這種情況嗎?或者我做錯了什麼?

+2

自動生成的代碼是設計師的責任心。你一定不要碰它。如果您需要擴展它或手動編寫接口,請使用子類化 –

+4

即使您*可以*這樣做,您絕對*不應該*。你甚至不應該在不同的類中訪問*字段,如果你想訪問表單中的文本框,你應該有一個工作表單的*實例*。 –

+1

我想如果你解釋了*爲什麼*你試圖將文本框定義轉換爲'static',我們可能會指出你正確的方向。主要是因爲你目前所做的是非常錯誤的。 – NotMe

回答

2

我相信,該設計是有缺陷的。 infoBox屬於表單,所以表單之外的對象不應該試圖訪問它。

這聽起來像你需要添加一個訪問器方法到你的表單類,如GetText(),以提供可見性的其他對象,而不會違反得墨忒耳定律。

0

不要.....做......吧!

揭露與控制的方法,我甚至建議暴露出控件屬性與調用驅動方法的變化,如果變化被稱爲跨線程的方式,它會得到妥善處理。

實施例:

public delegate void SetButtonTextDelegate(string text); 
public void SetButtonText(String text) 
{ 
    if(button.InvokeRequired) 
    { 
     Callback settext = new SetButtonTextDelegate(SetButtonText); 
     button.Invoke(settext, text); 
    } 
    else 
    { 
     button.Text = text; 
    } 
} 

然後,在任何外部類,只要調用SetButtonText( 「新的文本」);方法

0

如果您確信會有形式最多一個實例,您可以創建一個靜態屬性暴露的文本框中的文本。爲了做到這一點,你需要一個表單本身的靜態引用(我稱之爲InfoForm,比Form1更具信息性)。

爲此添加靜態Open方法。如果表單已打開,它會將其置於前臺,否則將打開它並將其分配給靜態字段_instance

public partial class InfoForm : Form 
{ 
    public InfoForm() 
    { 
     InitializeComponent(); 
    } 

    private static InfoForm _instance; 

    public static InfoForm Open() 
    { 
     if (_instance == null) { 
      _instance = new InfoForm(); 
      _instance.Show(); 
     } else { 
      _instance.BringToFront(); 
     } 
     return _instance; 
    } 

    protected override void OnClosed(EventArgs e) 
    { 
     base.OnClosed(e); 

     // Make sure _instance is null when form is closed 
     _instance = null; 
    } 

    // Exposes the text of the infoBox 
    public static string InfoText 
    { 
     get { return _instance == null ? null : _instance.infoBox.Text; } 
     set { if (_instance != null) _instance.infoBox.Text = value; } 
    } 
} 

現在你可以打開表單並訪問其infoTextTextBox這樣

InfoForm.Open(); 
InfoForm.InfoText = "Hello"; 
string msg = InfoForm.InfoText; 
相關問題