查找窗体中的每个控件

本文关键字:控件 窗体 查找 | 更新日期: 2023-09-27 17:51:05

我有很多SimpleButton (DevExpress控件)在我的形式。我想通过代码为他们设置AllowFocusfalse

foreach (Control x in this.Controls)
{
    if (x is SimpleButton)
    {
        ((SimpleButton)x).AllowFocus = false;
    }
}

当我使用这段代码时,什么都没有发生。它仍然允许对焦

查找窗体中的每个控件

从你的评论来看,很明显SImpleButton对象不是直接在表单上,所以迭代表单的控件集合不会返回那些。

你需要迭代GroupControl的Controls集合。

欢呼

已解决:

 foreach (Control x in groupControl1.Controls)
        {
            if (x is SimpleButton)
            {
                ((SimpleButton)x).AllowFocus = false;
            }
        }

试试这样做:

var buttons = this.Controls.OfType<Control>()
    .SelectMany(x => x.Controls.OfType<SimpleButton>());
foreach(var button in buttons)
      button.AllowFocus = false;

我建议更好地使用递归函数,我通常将所有控件放在主容器面板中,您只需要将该容器传递给function,其余的事情函数将为您做。

private void FocusControls(Control ctl)
        {
             if ((ctl.GetType() == typeof(GroupBox)) ||
                    (ctl.GetType() == typeof(DevExpress.XtraEditors.GroupControl)) ||
                    (ctl.GetType() == typeof(DevExpress.XtraEditors.PanelControl)) ||
                    (ctl.GetType() == typeof(DevExpress.XtraTab.XtraTabControl)) ||
                    (ctl.GetType() == typeof(DevExpress.XtraTab.XtraTabPage))
                    )
                {                    
                    foreach (Control obj in ctl.Controls)
                        FocusControls(obj);
                }
                 if (ctl.GetType() == typeof(SimpleButton))
                    {
                        SimpleButton objTemp = (SimpleButton)ctl;   
                        objTemp.AllowFocus = false;
                    }
        }

可能只是检查类型的情况:if (typeof(x) == typeof(SimpleButton))