问题
So I have been trying to make this layout. So far I have been able to do the 1st panel using the DockStyle.Left. However when I try to add the 2nd it keeps overlapping the 1st one. Also what would be the best way to add/manage the panels so when I add the 3rd one both panels get half of the UI height.
I'd like to avoid to use Drop and Drag tool.
Code with my panels so far:
Panel backPanel = new Panel();
backPanel.Dock = DockStyle.Fill;
Panel panel1 = new Panel();
panel1.Dock = DockStyle.Left;
panel1.BackColor = Color.Red;
Panel panel2 = new Panel();
panel2.Dock = DockStyle.Top;
panel2.BackColor = Color.Cyan;
backPanel.Controls.Add(panel1);
backPanel.Controls.Add(panel2);
this.Controls.Add(backPanel);
回答1:
Controls are docked in their Z-order, which is the visual layering of controls on a form along the form's Z-axis (depth). [Docs]
So the order of adding controls to the container is important. For example, for getting your expected layout you can add controls in this other:
var panel1 = new Panel() { BackColor = Color.Red, Dock = DockStyle.Left };
var panel2 = new Panel() { BackColor = Color.Green, Dock = DockStyle.Top };
var panel3 = new Panel() { BackColor = Color.Blue, Dock = DockStyle.Fill };
this.Controls.AddRange(new[] { panel3, panel2, panel1 });
Note:
- Don't avoid using designer of Windows Forms, unless you are creating some dynamic UI at run-time based on a custom logic.
- If you are using designer, you can simply use Document Outline window to change z-index of control. To show the window, go to View → Other Windows → Document Outline.
- If you are using designer, you can use Send to Back and Bring to Front commands from Layout Toolbar or by right click on the control.
- Using code, you can use
SendToBack
andBringToFrom
method of the control to bring it in front or send it to back of all controls. - Using code, you can use
SetChildIndex
method of the container control to set the z-index of the control. - As another option, you can mix two
SplitContainer
controls.
来源:https://stackoverflow.com/questions/46985991/windows-forms-side-panel-with-split-horizontal-panels-layout