首页 > 解决方案 > 如何更改 WinForms 面板中几个按钮的 FlatStyle MouseDownBackColor?

问题描述

我需要解析面板中的控件以更新一些按钮。我不明白如何访问它来更改按钮平面样式鼠标向下的颜色

public Color MouseDownBackColor {get; set;}

我知道我可以使用this.button1.FlatAppearance.MouseDownBackColor =,但在这种情况下,我可以从面板作为 var 访问按钮,并且不能以这种方式访问​​它。

更新:

foreach (Control control in button_panel.Controls)
{
    if (control is Button)
    {
       var button = (Button)control;
       button.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 0, 0, 0);
    }
}

标签: c#

解决方案


按钮的FlatStyle属性必须设置FlatStyle.Flat为工作。

您可以在类型检查之后使用类型转换(取消装箱) :Button

foreach (Control control in button_panel.Controls)
{
    if (control is Button)
    {
      var button = (Button)control;
      button.FlatStyle = FlatStyle.Flat;
      button.FlatAppearance.MouseDownBackColor = Color.Yellow;
    }
}

您也可以使用 Linq 编写此代码:

using System.Linq;

button_panel.Controls.OfType<Button>().ToList().ForEach(button =>
{
  button.FlatStyle = FlatStyle.Flat;
  button.FlatAppearance.MouseDownBackColor = Color.Yellow;
});

推荐阅读