C#WINFORM窗体传参的最佳实践

入VS2005后,大家可以发现子窗体操作父窗体不能沿用2003下的方法:把父窗体的空间访问属性由private改为public.IDE已经把控件声明这部分代码隐藏了,所以只有采用更加对象一点的方法。

父窗体与子窗体间的参数传递我采用的步骤如下:
1 父窗体中声明一个静态的父窗体类型的临时对象
        public static frmFather frmFatherTemp;

2 父窗体构造函数中对该变量赋值

        public frmFather()
        {
            InitializeComponent();
            frmFatherTemp = this;
        }


3 把要传递的参数设置为父窗体的一个属性,并设置访问器。访问其的set方法中进行了参数与父窗体控件绑定的操作。

        private string testValue;
       
        public string TestValue
        {
            get
            {
                return testValue;   
            }
            set
            {
                this.testValue = value;
                this.txtFather.Text = value;
            }
        }


4 父窗体参数传递事件中对要传递的参数赋值,并打开子窗体。父窗体的工作到此结束。

            this.TestValue = this.txtFather.Text;
            frmSon frm = new frmSon();
            frm.ShowDialog();


5 子窗体构造函数中设置传递参数与子窗体控件的绑定操作

        public frmSon()
        {
            InitializeComponent();
            this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
        }


6 子窗体回传事件中,对父窗体的临时对象的该参数属性赋值

        public frmSon()
        {
            InitializeComponent();
            this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
        }

ok。一切搞定!

全部代码如下:

frmFather.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace winFormParameterPass
{
    
public partial class frmFather : Form
    
{
        
public static frmFather frmFatherTemp;

        
private string testValue;
        
        
public string TestValue
        
{
            
get 
            
{
                
return testValue;    
            }

            
set 
            
{
                
this.testValue = value;
                
this.txtFather.Text = value;
            }

        }


        
public frmFather()
        
{
            InitializeComponent();
            frmFatherTemp 
= this;
        }


        
private void btnFather_Click(object sender, EventArgs e)
        
{
            
this.TestValue = this.txtFather.Text;
            frmSon frm 
= new frmSon();
            frm.ShowDialog();
        }

    }

}

frmSon.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace winFormParameterPass
{
    
public partial class frmSon : Form
    
{
        
public frmSon()
        
{
            InitializeComponent();
            
this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
        }


        
private void btnSon_Click(object sender, EventArgs e)
        
{
            frmFather.frmFatherTemp.TestValue 
= this.txtSon.Text;
            
this.Close();
        }

    }

}

例子程序:
/Files/heekui/winFormParameterPass.rar

以上想法给新手们一点参考,请高手指教。
posted on 2006-11-24 15:38  网际浪人  阅读(3013)  评论(6编辑  收藏  举报