解决这个老问题的另一种方法:我发现 老方法 是一种从任何项目中的类。这种旧方法包括创建一个临时类从头开始。
注意 A:关于旧方法:我知道,我知道,全局变量是邪恶的。但是,对于许多来这里寻找快速/灵活/suites-most-cases 解决方案的人来说,这可能是一个有效的答案,我还没有看到它发布。另一件事:这个解决方案是我实际使用的,作为我来到这个页面寻找的答案。
第一步:新的类文件从头开始如下。
namespace YourProjectNamespace
{
public class dataGlobal
{
public System.Windows.Forms.TextBox txtConsole = null;
// Place here some other things you might want to use globally, e.g.:
public int auxInteger;
public string auxMessage;
public bool auxBinary;
// etc.
}
}
注意 B:该类不是静态的,也没有静态成员,它允许创建多个实例以备不时之需。就我而言,我确实利用了这个功能。但是,事实上,您可以考虑将此类的 TextBox 设置为 public static 字段,以便 - 一旦初始化 - 在整个应用程序中始终相同。
第二步:然后你就可以在主窗体中初始化它了:
namespace YourProjectNamespace
{
public partial class Form1 : Form
{
// Declare
public static dataGlobal dataMain = new dataGlobal();
public Form1()
{
InitializeComponent();
// Initialize
dataMain.txtConsole = textBox1;
}
// Your own Form1 code goes on...
}
}
第三步:从您的其他类(或表单)调用Form1 的textBox1 的任何属性/方法:
namespace YourProjectNamespace
{
class SomeOtherClass
{
// Declare and Assign
dataGlobal dataLocal = Form1.dataMain;
public void SomethingToDo()
{
dataLocal.txtConsole.Visible = true;
dataLocal.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
dataLocal.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
string retrieveTextBoxValue = dataLocal.txtConsole.Text;
// Your own code continues...
}
}
}
[编辑]:
一种更简单的方法,特别是针对整个班级的TextBox 可见性,我在其他答案中没有看到:
第一步:在你的Main Form中声明并初始化一个辅助TextBox对象:
namespace YourProjectNamespace
{
public partial class Form1 : Form
{
// Declare
public static TextBox txtConsole;
public Form1()
{
InitializeComponent();
// Initialize
txtConsole = textBox1;
}
// Your own Form1 code goes on...
}
}
第二步:从您的其他类(或表单)调用Form1 的textBox1 的任何属性/方法:
namespace YourProjectNamespace
{
class SomeOtherClass
{
public void SomethingToDo()
{
Form1.txtConsole.Visible = true;
Form1.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
Form1.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
string retrieveTextBoxValue = Form1.txtConsole.Text;
// Your own code continues...
}
}
}
对[编辑]的评论:我注意到许多问题根本无法通过通常的建议来解决:“相反,请在表单上创建公共属性以获取/设置值你有兴趣”。有时会有几个属性/方法要实现......但是,我知道......最好的做法应该占上风:)