我有一个 Windows 窗体应用程序,其中一些控件已添加到设计器中。当我想更改某些内容(例如)启用 Form1.cs 中的文本框时,我只需使用:
textBox1.Enabled = true;
但现在我有一个名为 class1.cs 的独立类。
如何从静态函数 class1.cs 启用 textBox1?
注意:我没有尝试任何代码,因为我对此一无所知。
最佳答案
编辑:大量编辑。
public partial class Form1 : Form
{
// Static form. Null if no form created yet.
private static Form1 form = null;
private delegate void EnableDelegate(bool enable);
public Form1()
{
InitializeComponent();
form = this;
}
// Static method, call the non-static version if the form exist.
public static void EnableStaticTextBox(bool enable)
{
if (form != null)
form.EnableTextBox(enable);
}
private void EnableTextBox(bool enable)
{
// If this returns true, it means it was called from an external thread.
if (InvokeRequired)
{
// Create a delegate of this method and let the form run it.
this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable });
return; // Important
}
// Set textBox
textBox1.Enabled = enable;
}
}
关于c# - 从另一个类访问表单控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12983427/