我有以下方法可以正常工作:
button21.FlatAppearance.BorderSize = 0;
button21.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
正如你所看到的,我有很多按钮(~30),所以不要在每个按钮上应用样式 - 为什么不在Form_Load
事件上同时应用所有按钮?所以我写了这个方法:
public void ChangeButtonStyles()
{
foreach (Control con in this.Controls)
{
if (con is Button)
{
Button but = con as Button;
but.FlatAppearance.BorderSize = 0;
but.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
}
}
}
但它不起作用,因为当您将鼠标悬停在按钮上时 - 您可以看到背景更改,这证明but.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
无法正常工作
为什么代码不起作用?
public Form1()
{
InitializeComponent();
// works
//button21.FlatAppearance.BorderSize = 0;
//button21.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
// doesn't work
ChangeButtonStyles();
}
编辑:解决方案
public void ChangeButtonStyles()
{
foreach (Control con in this.Controls)
{
if (con is Button)
{
Button but = con as Button;
but.FlatAppearance.BorderSize = 0;
but.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
}
if (con is GroupBox)
{
foreach (Control subcon in con.Controls)
{
if (subcon is Button)
{
Button but = subcon as Button;
but.FlatAppearance.BorderSize = 0;
but.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
}
}
}
}
}
答案 0 :(得分:3)
您是否尝试过调试代码以查看它是否真的被执行了? this.Controls将返回顶级控件。如果按钮嵌套在其他控件中,则需要更加递归。
public void ChangeButtonStyles(Control source)
{
foreach (Control con in source.Controls)
{
if (con is Button)
{
Button but = con as Button;
but.FlatAppearance.BorderSize = 0;
but.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
}
else
{
ChangeButtonStyles(con);
}
}
}