龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

C#扩展:WinForm 控件选择器,WinForm仿jQuery选择器(2)

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
Form1是顶级控件,它包含了四个子控件:groupBox1、groupBox2、button1、button2。groupBox1和groupBox2中也包含了多个控件。层层包含最终形成了一个树型结构。 我们

Form1是顶级控件,它包含了四个子控件:groupBox1、groupBox2、button1、button2。groupBox1和groupBox2中也包含了多个控件。层层包含最终形成了一个树型结构。

 我们打造的WinForm的控件选择器,实质上就是一个树的遍历器。下是就是该选择器的参考实现代码: 

 1     public static IEnumerable<T> GetControls<T>(this Control control, Func<T, bool> filter) where T : Control
 2     {
 3         foreach (Control c in control.Controls)
 4         {
 5             if (c is T)
 6             {
 7                 T t = c as T;
 8                 if (filter != null)
 9                 {
10                     if (filter(t))
11                     {
12                         yield return t;
13                     }
14                     else
15                     {
16                         foreach (T _t in GetControls<T>(c, filter))
17                             yield return _t;
18                     }
19                 }
20                 else
21                     yield return t;
22             }
23             else
24             {
25                 foreach (T _t in GetControls<T>(c, filter))
26                     yield return _t;
27             }
28         }
29     }

 (代码中存在一处bug,请参见斯克迪亚的回复#4楼

  有了GetControls选择器,我们就可以在WinForm中进行一些“复杂”应用,示例如下(以图7为例): 

 

 1     // 构造函数
 2     public Form1()
 3     {
 4         InitializeComponent();
 5         //禁用所有Button
 6         this.GetControls<Button>(null).ForEach(b => b.Enabled = false);
 7         //反选groupBox1中CheckBox
 8         this.GetControls<CheckBox>(c => c.Parent == groupBox1)
 9             .ForEach(c => c.Checked = !c.Checked);
10         //将label1的前景色设为红色
11         this.GetControls<Label>(l => l.Name == "label1").FirstOrDefault().ForeColor
12             = Color.Red;
13     }

 附上常用的ForEach扩展:

1     public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
2     {
3         foreach (var item in source) 
4             action(item);
5     }
精彩图集

赞助商链接