如何更改表单中所有面板的背景色 [英] How to change BackColor of all my Panel in my Form
问题描述
我的工具需要帮助.我尝试使用 ColorDialog
更改我的 Color
我的 Panel
但是,它不起作用我想在我的 Form
中更改所有 Panel
的颜色.面板构造器:
I need help with my tool.
I have try change Color
my Panel
with ColorDialog
but, it does not work
I want change colors all Panel
in my Form
.
Panel constuctor:
Panel p = new Panel();
事件处理程序:
private void button104_Click_1(object sender, EventArgs e)
{
this.bg.FullOpen = true;
if (this.bg.ShowDialog() == DialogResult.OK)
{
this.setBgColor(this.bg.Color);
}
}
public void setBgColor(Color rgb)
{
p.BackColor = rgb;
}
推荐答案
您可以使用 System.Linq
扩展方法,OfType
选择特定类型的所有控件,如果你在循环中迭代它们,你可以设置它们的所有 BackColor
属性:
You can select all controls of a particular type by using the System.Linq
extension method, OfType
, and if you iterate over them in a loop, you can set all their BackColor
properties:
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
foreach (var panel in Controls.OfType<Panel>())
{
panel.BackColor = cd.Color;
}
}
}
请注意,这只会迭代直接属于表单本身的控件.如果任何面板在容器控件内,那么我们将需要查看每个控件以查看它是否包含任何面板.
Note that this only iterates over the controls belonging directly to the form itself. If any of the panels are inside a container control, then we will need to look through each control to see if it contains any panels.
我们可以为此编写一个辅助方法,它接收一个要检查的 Control
、一个用于 BackColor
的 Color
和一个Type
指定我们要为其设置背景颜色的控件类型.
We can write a helper method for this that takes in a Control
to inspect, a Color
to use for the BackColor
, and a Type
that specifies the type of control we want to set the back color for.
然后我们首先检查 Control
是否与我们要查找的类型相同,如果是,则将其设置为背景色.之后,我们遍历它的所有子项并再次递归调用它们的方法.这样,如果我们将父表单作为 Control
传递,我们将遍历所有控件:
Then we first check if the Control
is the same type as the one we're looking for, and if it is, set it's backcolor. After that, we loop through all it's children and recursively call the method again on them. This way, if we pass the parent form as the Control
, we will iterate through all the controls:
private void SetBackColorIncludingChildren(Control parent, Color backColor, Type controlType)
{
if (parent.GetType() == controlType)
{
parent.BackColor = backColor;
}
foreach(Control child in parent.Controls)
{
SetBackColorIncludingChildren(child, backColor, controlType);
}
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
// Pass 'this' to the method, which represents this 'Form' control
SetBackColorIncludingChildren(this, cd.Color, typeof(Panel));
}
}
这篇关于如何更改表单中所有面板的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!