C#Winform窗体利用单例子窗体传值父窗体
简述:最近在做C#和HALCON编程,要用到单例的参数由子窗体改变父窗体的值。此例为简化版
1,点击系统设置
2,弹出子窗体,在其输入修改参数后点修改按钮
3,点击确定按钮后,关闭子窗体后,主窗体textbox值改变
4,单例程序如下:
public class Student { //创建单例类,内部静态类方法 private Student() { }//私有构造函数 class Nested { internal static readonly Student instance = new Student(); } public static Student Instance { get { return Nested.instance; } } //创建字段和其属性 private string name; public string Name { get { return name; } set { name = value; } } private int chinses; public int Chinses { get { return chinses; } set { chinses = value; } } private int math; public int Math { get { return math; } set { math = value; } } }
5,子窗体程序
public Setting() { InitializeComponent(); } Student stu= Student.Instance; //创建单例类的对 private void Setting_Load(object sender, EventArgs e) { } private void BtnChange_Click(object sender, EventArgs e) { stu.Name = this.textBoxName.Text;//把子窗体textbox显示值赋给字段的属性 stu.Chinses = Convert.ToInt32(this.textBoxChinese.Text); stu.Math = Convert.ToInt32(this.textBoxMath.Text); }
6,父窗体程序
Student stu = Student.Instance;//创建单例类 private void MainForm_Load(object sender, EventArgs e) { this.tBName.Text = "Weber";//主窗体加载显示内容 this.tBChinese.Text = Convert.ToString(89); this.tBMath.Text = Convert.ToString(90); } private void ToolStripButton1_Click(object sender, EventArgs e) { Setting mySetting = new Setting(); mySetting.ShowDialog();//子窗体弹出 this.tBName.Text = stu.Name;//字段属性的值赋给textbox值 this.tBMath.Text = Convert.ToString(stu.Math); this.tBChinese.Text = Convert.ToString(stu.Chinses); }
7,总结
新手一枚,如有错误请指正!