C#根据控件名获取控件对象

C#根据控件名获取控件对象

2014年11月07日 11:05:57 CLeopard 阅读数 25001

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CLeopard/article/details/40889999

需求:在一个项目中,要实现一个控件选择功能,如果一个个的去判断,代码会十分难看,由于控件名有规律,

是否可以根据控件直接找到对应的控件对象?

实现:利用反射

可用于WPF:

object o = this.GetType().GetField(
    name
    , System.Reflection.BindingFlags.NonPublic 
        | System.Reflection.BindingFlags.Instance 
        | System.Reflection.BindingFlags.IgnoreCase
)
.GetValue(this);

return ((Control)o);

可用于Winform:​​​​

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";
}
原文地址:https://www.cnblogs.com/grj001/p/12224595.html