简体   繁体   中英

How to update a control in MDI parent form from child forms?

I looked to some similar questions but I didn't really get my answer, so I ask again hopefuly someone can explain it.

The situation:

I have a MDI form that has some menues and a status bar and stuff like that. Is the only way of altering text for status bar and doing other things to the parent form is to call it as static ? Or if not, can you please give an example for updating (for example) status bar that exist in parent form within the child forms?

Thanks!

You need to make the child forms take a parent form instance as a constructor parameter.
The children can save this parameter to a private field, then interact with the parent at will later.

For optimal design, you should abstract the parent from the child through an interface implemented by the parent, containing methods and properties that do what the children need. The children should then only interact with this interface.

public interface IChildHost {
    void UpdateStatusBar(string status);
    //Other methods & properties
}

public partial class ParentForm : IChildHost {
    public void UpdateStatusBar(string status) {
        ...
    }
    //Implement other methods & properties
}

public partial class ChildForm {
    readonly IChildHost host;
    public ChildForm(IChildHost parent) {
        this.host = parent;
    }

}

Form类已经公开了一个属性MdiParent,以确保相应地设置了父窗体的IsMdiContainer属性。

Another option is to use events (you can build these events into a base class and let all your child forms inherit from it):

// Code from Form 1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2();
        objForm2.ChangeStatus += new ChangeStatusHandler(objForm2_ChangeStatus);
        objForm2.Show();
    }
    public void objForm2_ChangeStatus(string strValue)
    {
        statusbar.Text = strValue;
    }
}

// Code From Form 2
public delegate void ChangeStatusHandler(string strValue);
public partial class Form2 : Form
{
    public event ChangeStatusHandler ChangeStatus;

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (PassValue != null)
        {
            PassValue(textBox1.Text);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM