简体   繁体   English

将控件及其子级放在C#中

[英]Bringing a control and its children to front in C#

I have a layering system which uses panels to contain different controls and GDI drawings, but I would like to change the order that they are displayed. 我有一个分层系统,该系统使用面板来包含不同的控件和GDI绘图,但是我想更改它们的显示顺序。 I have used the BringToFront() method on the panel, this does bring it to the front, but the controls that I have added to it are still displayed behind the other controls. 我已经在面板上使用了BringToFront()方法,这确实将其带到了前面,但是我添加到其中的控件仍然显示在其他控件的后面。 Is there a way that I can bring these controls up as well? 有没有办法我也可以调出这些控件?

Thanks. 谢谢。

EDIT: 编辑:

I should add that these panels are transparent. 我应该补充一点,这些面板是透明的。 And I add controls to the panel like panelName.Controls.Add(newControl); 然后将控件添加到面板上,例如panelName.Controls.Add(newControl);

You may sort the whole collection of child controls of your panel, to change the order in which they are displayed. 您可以对面板上所有子控件的集合进行排序,以更改其显示顺序。

Panel panel; //your top-most panel; this can be as well a Form

for (int i = 0; i < panel.Controls.Count; i++)
{
    panel.Controls.SetChildIndex(
        panel.Controls[i], panel.Controls.Count - 1 - i
    );
}

To keep this example simple the collection will be sorted in reversed order, but you are free to add any logic to calculate a new child index which fits your needs. 为了使此示例简单易懂,将以相反的顺序对集合进行排序,但是您可以随意添加任何逻辑来计算适合您需要的新子索引。
Obviously, the key here is the SetChildIndex method ( documentation ), allowing you to rearrange a controls index in the collection. 显然,这里的关键是SetChildIndex方法( documentation ),使您可以重新排列集合中的控件索引。

If you only want to sort objects of the type Panel (or another single type), then there is a quicker way to do so using LINQ: 如果您只想对Panel类型(或另一个单一类型)的对象进行排序,则可以使用LINQ更快地进行排序:

List<Panel> sorted = panel.Controls.OfType<Panel>().ToList();
sorted.Sort((p1, p2) => p1.TabIndex.CompareTo(p2.TabIndex));
panel.Controls.Clear();
panel.Controls.AddRange(sorted.ToArray());

This sorts all the panels comparing their tab index (just as an example). 这将比较所有面板的选项卡索引(仅作为示例)。 Should be easy to change this for other properties. 应该很容易将其更改为其他属性。

Another most common "mistake" lies in your *.Designer.cs -file. 另一个最常见的“错误”在于*.Designer.cs文件。 When dropping controls onto a form/panel, the order may have been reversed. 将控件放到窗体/面板上时,顺序可能已经颠倒。 Just take a look at your designer generated file and take look at the order. 只需查看您的设计器生成的文件并查看顺序即可。

You could loop through the list of controls on the panel ( contained within Panel.Controls ), and bring those to the front as well. 您可以遍历面板上的控件列表(包含在Panel.Controls中),并将它们也放在最前面。

Example: - Lets say you have a Panel p1 with 3 buttons b1, b2, and b3. 示例:-假设您有一个带有3个按钮b1,b2和b3的面板p1。

to bring p1 to the front and all it's controls you would do: 将p1置于最前面并进行所有控制,您将执行以下操作:

p1.BringToFront();
foreach(var c in p1.Controls){ c.BringToFront();}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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