【问题标题】:How to contol all elements on form如何控制表单上的所有元素
【发布时间】:2013-09-28 10:01:50
【问题描述】:

尝试启用或禁用表单上的某些元素(复选框和文本框) 阅读this post,然后稍微重新制作一下这段代码

代码:

    private void checkBoxEnableHotKeys_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBoxEnableHotKeys.Checked)
        {
            EnableControls(this.Controls, true);
        } //works perfect
        if (!checkBoxEnableHotKeys.Checked)
        {
            EnableControls(this.Controls, false);
        } //disable all controls
    }

    private void EnableControls(Control.ControlCollection controls, bool status)
    {
        foreach (Control c in controls)
        {   
            c.Enabled = status;         
            if (c is MenuStrip)
            {
                c.Enabled = true;
            }
            if (c.Controls.Count > 0)
            {
                EnableControls(c.Controls, status);
            }
        }
        checkBoxEnableHotKeys.Enabled = true; //not work 
    }

我在哪里做错了?为什么checkBoxEnableHotKeys.Enabled = true; 不起作用? (- 在 debagging 这部分代码以 false 传递的过程中 - 并且操作 = 不起作用 - 之前为假,之后为假......)

【问题讨论】:

  • 你到底想做什么?如果要禁用某些控件,请记住禁用一个控件也会禁用其所有子控件
  • 检查 checkBoxEnableHotKeys 的父级是否已禁用。如果是,那么您已启用其父级以启用子级
  • 哦!谢谢 !在checkBoxEnableHotKeys.Enabled = true; 之前添加tableLayoutPanel1.Enabled = true; - 现在可以了。 - 禁用一个控件也将禁用它的所有子控件 - 注意,谢谢

标签: c# .net winforms foreach controls


【解决方案1】:

我喜欢返回表单的所有子控件的方法 - 包括嵌套控件。

发件人:Foreach Control in form, how can I do something to all the TextBoxes in my Form?

我喜欢这个答案:

这里的技巧是 Controls 不是 List 或 IEnumerable 而是 ControlCollection。

我建议使用 Control 的扩展,它将返回更多内容..可查询;)

public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }

那么你可以这样做:

foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
    // Apply logic to the textbox here
}

【讨论】:

  • 嘿,我希望我意识到你可以在我以前的工作中获得像这样的 OfType 属性。在许多项目中,我有一个递归方法可以遍历所有控件/控件的子项,并根据类型执行大量不同的操作。这会让它变得更干净。
猜你喜欢
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
相关资源
最近更新 更多