1

我有以下方法可以正常工作:

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;
                }
            }
        }
    }
}
4

1 回答 1

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);
        }
    }
}
于 2012-08-30T18:54:01.000 回答