Skip to content

Latest commit

 

History

History
89 lines (71 loc) · 2.47 KB

从0自学C#06--多窗体共用对象.md

File metadata and controls

89 lines (71 loc) · 2.47 KB

如何实现子窗体与父窗体共用同一个实体对象

上一篇介绍了通过委托事件的方式,实现了子窗体调用父窗体的控件。本文将用参数传递的方式,实现共用一个实体对象。

本文所用的代码,也是在上一篇基础上做修改。

1.父窗体

将共用实体对象innoBERT作为子窗体构造函数的参数。代码如下“修改此行”部分。

if (subFormPPGTx[i] == null || subFormPPGTx[i].IsDisposed)
                    {
                        subFormPPGTx[i] = new SubFormPPG(innoBERT, i);//修改此行
                        subFormPPGTx[i].Text = formTitle;
                        subFormPPGTx[i].Name = formName;
                        //subFormPPGTx[i].Tag = i;
                        subFormPPGTx[i].SendToParent += new SubFormPPG.SendFun(RecvInfo);
                        subFormPPGTx[i].Show(this);
                    }
                    else
                    {
                        subFormPPGTx[i].WindowState = FormWindowState.Normal;
                        subFormPPGTx[i].Activate();
                    }

2.子窗体

首先定义一个类字段,然后修改子窗体的构造函数,添加参数,用于接收父窗体传递的实体对象。这样就可以在子窗体里,调用实体对象innoBERT。

InnolightBERT innolightBERT;
bool formStatus = false;
private int ID;

public delegate void SendFun(int number);
public event SendFun SendToParent;

public SubFormPPG(InnolightBERT innoBERT, int ID)
{
    InitializeComponent();
    this.innolightBERT = innoBERT;//接收对象
    this.ID = ID;
}

3.应用

子窗体调用共用实体对象的属性。

private void SubFormPPG_Load(object sender, EventArgs e)
{
    this.GetPPGSetting(this.ID);
}

private void GetPPGSetting(int channel)
{
    try
    {
        switch (channel)
        {
            case 0:
                this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx1_Swing;
                break;

            case 1:
                this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx2_Swing;
                break;

            case 2:
                this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx3_Swing;
                break;

            case 3:
                this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx4_Swing;
                break;

            default:
                return;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}