微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用反射设置控件的属性

如何解决使用反射设置控件的属性

如何获取/设置Control(在本例中为Button)的属性

我尝试过这种方式:

Type t = Type.GetType("System.Windows.Forms.Button");

PropertyInfo prop = t.GetType().GetProperty("Enabled");

if (null != prop && prop.CanWrite && prop.Name.Equals("button1"))
{
    prop.SetValue(t,"False",null);
}

但t为空。怎么了?

解决方法

首先,您需要 instance 将属性设置为button1

 object instance = button1;

您可能想找到它,例如让我们扫描所有MyForm类型的打开形式,并用Button "button1"查找Name

 using System.Linq;

 ...

 object instance = Application
   .OpenForms
   .OfType<MyForm>()
   .SelectMany(form => form.Controls.Find("button1",true))
   .OfType<Button>()
   .FirstOrDefault();

 ...

然后我们就准备好进行反射了:

 var prop = instance.GetType().GetProperty("Enabled");

 if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool))
   // we set false (bool,not string "False") value
   // for instance button1   
   prop.SetValue(instance,false,null);  

编辑:如果要通过Typestring获取Type.GetType(...),则需要程序集限定名称

 string name = typeof(Button).AssemblyQualifiedName;

你会得到类似的东西

System.Windows.Forms.Button,System.Windows.Forms,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089

演示:

Type t = Type.GetType(
  @"System.Windows.Forms.Button,PublicKeyToken=b77a5c561934e089");

MessageBox.Show(t.Name);
  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。