【问题标题】:Not changing the properties for fields via control array不通过控件数组更改字段的属性
【发布时间】:2014-10-31 14:50:05
【问题描述】:

我有 WinForm,那里有很多控件,在某些时候我需要更改其中一些的属性。所以,我创建 Control 数组 并确定应该改变

controls = new Control[] {loadFromFile_btn, logout_btn, postBtn, waitFrom_tb, waitTo_tb, messageTB, recurs_check};
ChangeStatus.activStatus(controls);

然后在我的类中ChangeStatus对所有这些元素进行更改都在一个数组中

public static void activStatus(Control[] controlObj)
    {
        for (int i = 0; i < controlObj.Count() - 1; i++)
        {
            controlObj[i].BeginInvoke((Action)delegate
            {
                if (controlObj[i] is TextBox || controlObj[i] is CheckBox || controlObj[i] is Panel)
                    controlObj[i].Enabled = true;
                else
                {
                    controlObj[i].BackColor = Color.DarkGray;
                    controlObj[i].Enabled = true;
                }
            });
        }
    }

但我有一个问题...更改仅适用于数组中的最后一个元素。请帮帮我..

【问题讨论】:

    标签: c# arrays winforms controls


    【解决方案1】:

    这是因为closure。尝试将i 存储在局部变量中并在您的匿名方法中使用它

     for (int i = 0; i < controlObj.Count() - 1; i++)
        {
            int j = i;
            controlObj[i].BeginInvoke((Action)delegate
            {
                if (controlObj[j] is TextBox || controlObj[j] is CheckBox || controlObj[j] is Panel)
                    controlObj[j].Enabled = true;
                else
                {
                    controlObj[j].BackColor = Color.DarkGray;
                    controlObj[j].Enabled = true;
                }
            });
        }
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2020-07-09
      相关资源
      最近更新 更多