本文共 629 字,大约阅读时间需要 2 分钟。
需求:在一个项目中,要实现一个控件选择功能,如果一个个的去判断,代码会十分难看,由于控件名有规律,是否可以根据控件直接找到对应的控件对象?
实现:利用反射
可用于WPF:
object o = this.GetType().GetField(name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); return ((Control)o);
private void button2_Click(object sender, EventArgs e) { ((Button)(this.Controls.Find("button1", false)[0])).Text = "123"; }
WPF类似于Controls.Find:
private void Button_Click(object sender, RoutedEventArgs e) { ((Button)this.FindName("Button1")).Content = "123"; }
转载地址:http://gtnmb.baihongyu.com/