问题
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?
Thanks.
EDIT:
I should add that these panels are transparent. And I add controls to the panel like panelName.Controls.Add(newControl);
回答1:
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.
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.
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.
回答2:
You could loop through the list of controls on the panel ( contained within Panel.Controls ), and bring those to the front as well.
Example: - Lets say you have a Panel p1 with 3 buttons b1, b2, and b3.
to bring p1 to the front and all it's controls you would do:
p1.BringToFront();
foreach(var c in p1.Controls){ c.BringToFront();}
来源:https://stackoverflow.com/questions/19793064/bringing-a-control-and-its-children-to-front-in-c-sharp