简体   繁体   中英

C# Winform MDI Form with Split Container - MdiChildren is empty

I am creating a C#.Net 4.8 Winform app with one MDI Form. This MDI Form has several panels and a split container.

When adding a childform I use the following code:

frm.Text = formTitleText;
frm.MdiParent = this;
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
frm.Dock = DockStyle.Fill;
panelDeskTop.Controls.Add(frm);
panelDeskTop.Tag = frm;
frm.BringToFront();
lblTitleChildForm.Text = $"{frm.Text}({this.MdiChildren.Length})";
frm.Show();

The form shows in the panel, but is not added as a MDI Child. The Parent (This) is the MDI Parent and has property of IsMDIContainer. So the this.MdiChildren.Length is always 0.

Not sure why?

Thanks in advance.

It's expected. You've set another parent for it: panelDeskTop.Controls.Add(frm); .

Consider the following points:

  • An MDI parent form has a control of type MdiClient . When you set MdiParent of a form, basically you are adding it to the controls collection of the MdiClient control.

  • When you ask MdiChildren of an MDI parent form, it returns the child forms of the MdiClient.

  • A form or a control, can have only one parent at time, and when you add it to controls collection of new parent, it will be removed from controls collection of the old parent.

Now I believe, it's clearer:

frm.MdiParent = this;
...
...
panelDeskTop.Controls.Add(frm);

The last line, removes the form from MdiChildren of the parent. That's why the array is empty.

Do you really need MDI?

It looks like you don't need MDI. If the child form is gonna fill the main panel without showing titlebar, then it basically means it doesn't need an mdi parent. Just make it a non-toplevel and add it to the controls collection of the main panel and show it.

Resizable sidebar for MDI parent

If you want have a resizable sidebar for MDI parent, then it's enough to Dock a panel and the splitter to left of the parenr, and then the right side will be occupied by the MdiClient. For example:

var mdiParent = new Form() { Size = new Size(700, 450), Text = "parent" };
mdiParent.Load += (obj, args) =>
{
    mdiParent.IsMdiContainer = true;
    mdiParent.Controls.Add(new Splitter()
    { Dock = DockStyle.Left, BackColor = Color.White, Width = 8 });
    mdiParent.Controls.Add(new Panel()
    { Dock = DockStyle.Left, BackColor = Color.Black });
    var child1 = new Form()
    { MdiParent = mdiParent, Text = "child1", Size = new Size(400, 300) };
    var child2 = new Form()
    { MdiParent = mdiParent, Text = "child2", Size = new Size(400, 300) };
    child1.Show();
    child2.Show();
};
mdiParent.ShowDialog();

在此处输入图像描述

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