【问题标题】:How to change property of all buttons in windows from?如何更改窗口中所有按钮的属性?
【发布时间】:2017-07-08 06:01:27
【问题描述】:

我在Form1 上有一些按钮。我想将他们的FlatStyle 属性设置为FlatStyle.Popup。 我搜索并编写了一些代码如下:

// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }



 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }

但是当我在代码的热线中使用GetAccessToAllButtons() 时,VS 会产生这个错误:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' 是一个 'method',在给定的上下文中无效

我的错误是什么?

编辑:我在here 的参考错过了()。这是一个公认的答案!在我的参考中,我们有不同的情况吗?还是只是一个错字?

【问题讨论】:

  • 你有多少个按钮?如果是 10 或 20,您可以创建一个数组来保存对按钮变量的引用,而不是编写递归?例如var buttons = new Button[] {button1, button2, button3 } 还是你添加按钮动态形成?
  • @shahkalpesh 我有 14 个按钮,并在加载表单时添加它们,而不是动态地。
  • 虽然您已经得到答案,但我认为将 14 个变量名称添加到按钮数组而不是尝试在运行时查找按钮是可以的。

标签: c# winforms button visual-studio-2013


【解决方案1】:

OfType 是通用方法,您必须将其用作方法。 只需将该行替换为以下内容:

ButtonsList = GetAccessToAllButtons(this).OfType<Button>().ToList();

另外我会推荐你​​写方法如下:

public List<Button> GetAllButtons(Form f)
{
    List<Button> resultList = new List<Button>();
    foreach(Control a in f.Controls)
    {
        if(a is Button)
        {
            resultList.Add((Button)a);
        }
    }
    return resultList;
}

并以这种方式使用它:

var myBtns = GetAllButtons(yourForm);
foreach (var btn in myBtns)
{
    btn.FlatStyle = FlatStyle.Popup;
}

【讨论】:

    【解决方案2】:
    .OfType<Button>
    

    OfType 是一种方法,因此您在其末尾缺少()。应该是:

    .OfType<Button>()
    

    【讨论】:

      【解决方案3】:

      你需要这样打电话:OfType&lt;Button&gt;().ToList();

      以下链接将帮助您了解 OfType 方法:

      https://msdn.microsoft.com/en-us/library/bb360913(v=vs.110).aspx

      最好用这种方式:

      foreach (var control in this.Controls)
      {
         if (control.GetType()== typeof(Button))
         {
             //do stuff with control in form
         }
      }
      

      【讨论】:

      • 非常有用的答案。谢谢。
      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 2021-12-18
      • 2019-10-26
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多