場景需求是在窗體加載完成后掉用工具類的方法,工具類中獲取窗體的多個控件對象進行賦值。 注: 博客主頁: 實現(xiàn)新建一個窗體程序,在窗體Forn1中拖拽一個label控件和TextBox控件。
然后進入到窗體的代碼中 在構造方法前聲明靜態(tài)類變量 public static Form1 form1 = null; 在構造方法中將當前窗體賦值給上面聲明的變量 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 = "流氓"; } } } 此時通過窗體類調用靜態(tài)的窗體變量,進而調用控件對象時會提示如下
這是因為控件默認是保護級別的,即所屬窗體私有的,要修改控件的modifilers屬性改為public。 來到窗體設計頁面,右鍵控件-屬性 然后雙擊窗體進入窗體的load事件中 在窗體加載完的方法中調用工具類的方法 private void Form1_Load(object sender, EventArgs e) { SetParam.setControlText(); } 運行效果
|
|