2011-10-26 45 views
0

這似乎是完全不合理的要求,但我一直在設計一個多面板的真實設備模擬器,它有很多不同的屏幕,我目前的方法是隻添加代碼中的所有屏幕對象,並在我切換時處理它們到另一個屏幕。是否可以通過方法定義類作用域對象?

我有一些固定的對象,這是真正的設備按鈕,已經定義和到位。事情是,我在方法中分隔每個面板結構,例如:buildLogin(),buildMainScreen()等,我需要從這些方法編輯一些屏幕對象,如啓用時將啓用的功能標籤的顏色更改爲綠色或白色如果禁用。

我的問題是:是否有可能從整個類中可訪問的方法聲明對象,就像它是在變量聲明部分中定義的一樣?這將是像PHP中的GLOBAL。

我無法像在任何事物上一樣聲明它,因爲當我處理這些對象時,我不能「重新創建」它們,因爲父母或重新使用已處理的對象或其他東西...

[編輯]示例代碼:

public partial class frmMain : Form 
{ 
    //I could as well do this: 
    //Button button1 = new Button(); 

    public frmMain() 
    { 
     buildLogin(); 
    } 

    private void buildLogin() 
    { 
     Panel panel1 = new Panel(); 
     Controls.Add(panel1); 

     //But then, there is no way to do this: 
     // if (button1.IsDisposed == true) //because of the panel, or smthing 
     Button button1 = new Button(); 
     panel1.Controls.Add(button1); 

     button1.Click += (s, f) => { panel1.Dispose(); buildMainMenu(); }; 
    } 

    private void buildMainMenu() 
    { 
     Panel panel2 = new Panel(); 
     Controls.Add(panel2); 

     Button button2 = new Button(); 
     panel2.Controls.Add(button2); 
    } 

    //This was created from the Designer and is class-scoped 
    private void btn_Frame_TSK1_Click(object sender, EventArgs e) 
    { 
     //Here, I have no access to the objets I've created programatically. 
     //button1.Text = "Text changed!"; 
    } 
} 
+0

在這個設計中肯定會出現錯誤,提供一些代碼,例如如何創建屏幕以及何時需要訪問這樣的全局對象? – sll

+0

你有沒有想過使用面向對象的設計?這使它更容易。 – PVitt

+0

我對你之後的事情有些模糊 - 你不能只聲明一個類作用域屬性/字段,然後在你的方法中設置它嗎?否則,可能重構傳遞的參數,然後你可以修改它們......這聽起來像你的程序結構可能是什麼需要改變這裏... – Chris

回答

0

如果你想確保事情總是完全動態的,總是在後面的代碼完成後,你可能會想看看搜索的控制你已經在Controls集合中創建。

例如,確保給button1一個ID值(button1.ID =「textUpdatedButton」),它將從您創建的其他控件中唯一標識它。然後使用FindControl或在Controls集合上進行搜索以找到具有要在事件處理程序中定位的ID的控件。

//This was created from the Designer and is class-scoped 
private void btn_Frame_TSK1_Click(object sender, EventArgs e) 
{ 
    Control control = this.FindControl("textUpdatedButton"); 
    if(control != null && control is Button){ 
     Button button1 = (Button)control; 
     button1.Text = "Text changed!"; 
    } 
} 

另外,爲了使事情看起來更像是一個變量,你可以使用屬性來隱藏控制發現(如前所述):

private Button Button1 { 
    get { return (Button)this.FindControl("textUpdatedButton"); } 
} 

//This was created from the Designer and is class-scoped 
private void btn_Frame_TSK1_Click(object sender, EventArgs e) 
{ 
    if(this.Button1 != null){ 
     this.Button1.Text = "Text changed!"; 
    } 
} 

實際的實施將改變與你如何建立建立你的控制,但基本上這種方法可以讓你在你的代碼中動態地構建一切,如果你需要這樣做的話。只記得使用標識符讓你以後找到東西。

+0

迄今爲止的最佳解決方案... – henriquesirot

0

在類級別定義您的對象,爲Static。這樣它就可以從類的所有實例的所有方法中訪問(處置實例不會影響它)。

+0

不,仍然說我不能訪問這一行中的處置對象「panLoginMenu.Controls.Add(btnRemember);」 btn記住是靜態控制... – henriquesirot

相關問題