場景
需求是在窗體加載完成後掉用工具類的方法,工具類中擷取窗體的多個控件對象進行指派。
實作
建立一個窗體程式,在窗體Forn1中拖拽一個label控件和TextBox控件。

然後進入到窗體的代碼中
在構造方法前聲明靜态類變量
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 = "流氓";
}
}
}
此時通過窗體類調用靜态的窗體變量,進而調用控件對象時會提示如下
這是因為控件預設是保護級别的,即所屬窗體私有的,要修改控件的modifilers屬性改為public。
來到窗體設計頁面,右鍵控件-屬性
然後輕按兩下窗體進入窗體的load事件中
在窗體加載完的方法中調用工具類的方法
private void Form1_Load(object sender, EventArgs e)
{
SetParam.setControlText();
}
運作效果