場景需求是在窗體加載完成后掉用工具類的方法,工具類中獲取窗體的多個(gè)控件對象進(jìn)行賦值。 注: 博客主頁: 實(shí)現(xiàn)新建一個(gè)窗體程序,在窗體Forn1中拖拽一個(gè)label控件和TextBox控件。
然后進(jìn)入到窗體的代碼中 在構(gòu)造方法前聲明靜態(tài)類變量 public static Form1 form1 = null; 在構(gòu)造方法中將當(dāng)前窗體賦值給上面聲明的變量 public Form1() { InitializeComponent(); form1 = this; } 窗體完整代碼: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FromParamTest { public partial class Form1 : Form { public static Form1 form1 = null; public Form1() { InitializeComponent(); form1 = this; } private void Form1_Load(object sender, EventArgs e) { SetParam.setControlText(); } } }
新建工具類setParam using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FromParamTest { public class SetParam { public static void setControlText() { Form1.form1.label1.Text = "霸道"; Form1.form1.textBox1.Text = "流氓"; } } } 此時(shí)通過窗體類調(diào)用靜態(tài)的窗體變量,進(jìn)而調(diào)用控件對象時(shí)會提示如下
這是因?yàn)榭丶J(rèn)是保護(hù)級別的,即所屬窗體私有的,要修改控件的modifilers屬性改為public。 來到窗體設(shè)計(jì)頁面,右鍵控件-屬性 然后雙擊窗體進(jìn)入窗體的load事件中 在窗體加載完的方法中調(diào)用工具類的方法 private void Form1_Load(object sender, EventArgs e) { SetParam.setControlText(); } 運(yùn)行效果
|
|
|