Winform中怎样在工具类中对窗体中多个控件进行操作(赋值)
生活随笔
收集整理的這篇文章主要介紹了
Winform中怎样在工具类中对窗体中多个控件进行操作(赋值)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
需求是在窗體加載完成后掉用工具類的方法,工具類中獲取窗體的多個控件對象進行賦值。
注:
博客主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
新建一個窗體程序,在窗體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();}運行效果
?
總結
以上是生活随笔為你收集整理的Winform中怎样在工具类中对窗体中多个控件进行操作(赋值)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中使用cutecharts实
- 下一篇: ElementUI项目中怎样引用Jque