如何在 WinForms 中控制对接顺序

我正在寻找一种方法来控制的顺序,其中的项目停靠在我的控制顶部。

我已经注意到,当我将子元素添加到控件(在设计器中或通过代码)时,最新的子元素总是位于顶部。我希望年龄较小的孩子在最底层,年龄最大的孩子在最顶层。

有没有办法通过代码实现这一点?在 WinForms 设计器中,RightClick->Order->BringToFront/SendToBack正在做一些类似于我想要做的事情,但是如何通过编程来实现呢?

65582 次浏览

A control has two methods to achieve what you are looking for: BringToFront and SendToBack.

Go to View → Other windows → document outline.

In that window drag the controls so the docking is as you like it to be.

The order in which the controls are being added to the Controls collection determines the docking order.

Use these methods:

myControl.SendToBack();
myControl.BringToFront();

As you said, the newest control added to the controls collection is the one on top. If you need a newer control to be added at the bottom, I'll suggest to create a list of controls, add the controls to the list, reverse the list and add the list to the controls collection.

List<Control> controls = new List<Control();
controls.Add(new myFirstControl());
controls.Add(new mySecondControl());
controls.Reverse();
this.Controls.AddRange(controls.ToArray());

Use the FlowLayoutPanel it does exactly what you want.

(For the sake matter of showing another option): In Visual Studio 2012 (and later):

  1. Select the Control you want to Move to the Front (or back);
  2. Click in the below marked buttons (Bring to Front / Send to Back); enter image description here

This will give you the possibility to rearrange the Controls to your desired order.

Note that when doing this programmatically, then there's a very easy way to achieve this, namely:

containerPanel.Controls.SetChildIndex(Element, 0); //sends element to the bottom of the list