通过等式更改所有按钮的背景颜色 [英] Change all buttons background color by equation

查看:30
本文介绍了通过等式更改所有按钮的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为 Design

I have created a class named Design

包含此代码

public static void Edit(Form frm, Color bkColor, Color btnColor,Color pnlColor)
{
    frm.BackColor = bkColor;
    frm.RightToLeft = RightToLeft.Yes;
    frm.RightToLeftLayout = true;
    foreach (Button btn in frm.Controls.OfType<Button>())
    {
        btn.BackColor = btnColor;
    }
    foreach (Panel pnl in frm.Controls.OfType<Panel>())
    {
        pnl.BackColor = pnlColor;
    }
}

我用以下形式调用它:

Design.Edit(this, Color.Blue, Color.Green, Color.Yellow);

现在它在表单背景上运行良好,但在面板和按钮上根本不起作用

NOW it works good on the form background BUT on the panel and buttons not working at all

推荐答案

您需要在表单的所有控件内递归搜索您的控件.看看 公认的答案,实现了一种非常好的递归方法.

You need a recoursive search of your control inside of all the controls of the form. Look that accepted answer that implement a very good recoursive approach.

这样做:

frm.Controls.OfType<Button>()

您只在表单的第一层控件中进行搜索,因此如果您在面板或其他元素中有一个按钮(99,999999% 的情况),您的 foreach 将无法找到它.

you search only in the first layer of controls of your forms, so if you've a button inside a panel or another element (the 99,999999% of the situations) your foreach cannot find it.

根据您的问题调整已接受的答案:

adapting the Accepted answer at your Question:

public IEnumerable<Control> GetAll(this Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => ctrl.GetAll(type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

[...]

foreach (Button btn in frm.GetAll(typeof(Button)))
    {
        btn.BackColor = btnColor;
    }

L-

这篇关于通过等式更改所有按钮的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆