2016-10-10 19 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

相关问题