zoukankan      html  css  js  c++  java
  • 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";
    }
  • 相关阅读:
    一些动规题
    洛谷P1717 钓鱼
    一堆递推题
    义冢oj P5033打气球
    义冢oj P5032生理周期
    Proud Merchants HDU
    739B
    Lost Cows POJ
    并查集负值根表集合大小的写法
    [Poi2011]Tree Rotations线段树合并
  • 原文地址:https://www.cnblogs.com/grj001/p/12224595.html
Copyright © 2011-2022 走看看