我有一个Windows窗体应用程序,其中一些控件添加到设计器中.当我想要更改某些内容(LIKE)时从Form1.cs中启用一个文本框
我只是用
textBox1.Enabled = true;
Run Code Online (Sandbox Code Playgroud)
但现在我有一个名为class1.cs的分离类
我如何从静态函数class1.cs启用textBox1?
{注意}我没有尝试任何代码,因为我完全不知道这样做.
vr_*_*ver 14
这只是另一种方法:
TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;
Run Code Online (Sandbox Code Playgroud)
Lig*_*ker 11
编辑:很多编辑.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
You shouldn't really change UI controls in your Form from your class1, but instead create a method or a property in class1 that would tell if the textbox should be enabled or not.
Example:
// I changed the name class1 to MySettings
public class MySettings
{
public bool ShouldTextBoxBeEnabled()
{
// Do some logic here.
return true;
}
// More generic
public static bool SetTextBoxState(TextBox textBox)
{
// Do some logic here.
textBox.Enabled = true;
}
// Or static property (method if you like)
public static StaticShouldTextBoxBeEnabled { get { return true; } }
}
Run Code Online (Sandbox Code Playgroud)
Then in your form:
MySettings settings = new MySettings();
textBox1.Enabled = settings.ShouldTextBoxBeEnabled();
// Or static way
textBox1.Enabled = MySettings.StaticShouldTextBoxBeEnabled;
// Or this way you can send in all textboxes you want to do the logic on.
MySettings.SetTextBoxState(textBox1);
Run Code Online (Sandbox Code Playgroud)