问题描述
我有一个分层系统,该系统使用面板来包含不同的控件和GDI绘图,但是我想更改它们的显示顺序.我已经在面板上使用了BringToFront()
方法,但这确实将它带到了前面,但是我添加到其中的控件仍然显示在其他控件的后面.有没有办法我也可以调出这些控件?
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. 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. Is there a way that I can bring these controls up as well?
谢谢.
我应该补充一点,这些面板是透明的.然后将控件添加到面板上,例如panelName.Controls.Add(newControl);
I should add that these panels are transparent. And I add controls to the panel like 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
);
}
为使此示例简单易懂,将以相反的顺序对集合进行排序,但是您可以随意添加任何逻辑来计算新的符合您需要的子索引.
显然,此处的关键是SetChildIndex
方法(文档),您可以在集合中重新排列控件索引.
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.
如果您只想对Panel
类型(或另一种单一类型)的对象进行排序,则可以使用LINQ更快地做到这一点:
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:
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.
另一个最常见的错误"在于您的*.Designer.cs
文件.将控件放到窗体/面板上时,顺序可能已颠倒.只需看看您的设计器生成的文件并查看顺序即可.
Another most common "mistake" lies in your *.Designer.cs
-file. 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.
这篇关于将控件及其子级放在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!