2016-10-10 20 views
2

目前我有多個類,其中之一被稱爲'可變類',其中我的值從其他類獲得。訪問空隙這些值僅僅是:如何讓我的類變量屬性進入Winform控件?

Private void (Variables vb) 
{  
} 

然而Winforms中的 '負載' 部,

private void Form1_Load(object sender, EventArgs e) 
    { 
    } 

從變量類別:

public class Variables 
{ 
public int Node { get; set; } 
} 

object sender, EventArgs e部分佔據我放置參數的空間。有沒有什麼辦法可以從winform上的類Variables獲得Node

+0

然後放入窗體的構造函數中 - 您可以將變量傳遞給窗體的'Load'事件。 –

+2

你可能需要在winforms/C#上做一個教程。聽起來像你很新 –

+0

你究竟想要做什麼? – Lodestone6

回答

0

我不是100%確定這是你在找什麼,但我想我可以幫忙。

namespace Example 
    { 
     public partial class Form1 : Form 
     { 
      public Form1() 
      { 
       InitializeComponent(); 
      } 
      //class which can be used anywhere in the namespace 
      public class exampleClass 
      { 
       public const string SETSTATE = "0"; 
       public const string GETSTATE = "1"; 
       public const string SETVALUE = "2"; 
       public const string GETVALUE = "3"; 
       public const string SENDFILE = "4"; 
       public const string STATE_RP = "129"; 
       public const string VALUE_RP = "131"; 
       public const string STATUS_RP = "128"; 
      } 
     } 
    } 

您可以在Form1中的任何位置使用exampleClass及其任何隨附成員。您無需將其傳遞至表單中的任何位置即可使用。你可以在以後添加一個功能,使用它直接喜歡:

void exampleF() 
     { 
      //note that when you are accessing properties of UI elements from 
      //a non-UI thread, you must use a background worker or delegate 
      //to ensure you are doing so in a threadsafe way. thats a different problem though. 
      this.txtYourTextBox.txt = exampleClass.GETSTATE; 
     } 
0

也許你嘗試它實際上是用MVP-格局的WinForms。非常好的主意。 然後,您可以使用DataBinding將您的Forms-Controls綁定到您的「Variables classes」屬性。您的變量類需要演示者角色,您的表單是視圖,而您的模型是變量類數據的來源。

不幸的是,該模式使用一些先進的機制,你必須處理。

欲瞭解更多信息,您可以在這裏乘坐先來看看: Databinding in MVP winforms

2

你的方法Form1_Load事件處理(因爲它通常被稱爲發生的一些事件的結果)。 「加載」事件由WinForms定義,因此您無法更改參數爲object senderEventArgs e的事實。

WinForms在您顯示錶單之前創建Form1類的一個實例。每當事件發生在窗體上時,該同一對象上的事件處理程序就會被調用。

所以,你可以存儲你的Form1類的字段的值和屬性:

public class Form1 : Form 
{ 
    Variables _myVariables; 

    public Form1() 
    { 
     InitializeComponent(); 
     _myVariables = new Variables() { Node = 10 } 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     MessageBox.Show("The current value of _myVariables.Node is: " + _myVariables.Node); 
    } 
} 

如果您Variables對象的形式之外創建的,那麼你可以把它傳遞到您的Form1構造:

public class Form1 : Form 
{ 
    Variables _myVariables; 

    public Form1(Variables variables) 
    { 
     InitializeComponent(); 
     _myVariables = variables; 
    } 

    // ... 
} 


// Then, somewhere else: 

var variables = new Variables() { Node = 10 }; 
var myForm = new Form1(variables); 
myForm.Show(); 
// or: Application.Run(myForm); 
+0

它現在工作!感謝堆! – ErnestY

相關問題