博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

WinForm 选择器

Posted on 2011-07-20 09:44  codingsilence  阅读(240)  评论(0编辑  收藏  举报

public static IEnumerable<T> GetControls<T>(this Control control, Func<T, bool> filter) where T : Control
        {
            foreach (Control c in control.Controls)
            {
                if (c is T && (filter == null || filter(c as T)))
                {
                    yield return c as T;
                }
                foreach (T _t in GetControls<T>(c, filter))
                    yield return _t;
            }
        }

        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var item in source)
                action(item);
        }

 

//禁用所有Button
     this.GetControls<Button>(null).ForEach(b => b.Enabled = false);
     //反选groupBox1中CheckBox
     this.GetControls<CheckBox>(c => c.Parent == groupBox1)
         .ForEach(c => c.Checked = !c.Checked);
     //将label1的前景色设为红色
     this.GetControls<Label>(l => l.Name == "label1").FirstOrDefault().ForeColor
         = Color.Red;