【问题标题】:Set property of control using reflection使用反射设置控件的属性
【发布时间】:2021-02-21 16:21:41
【问题描述】:

如何获取/设置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 为空。这里有什么问题?

【问题讨论】:

  • t.GetProperty() 而不是 t.GetType().GetProperty()
  • prop.Name 将是 Enabled,而不是 button1
  • 但是 t 对象一直为空。
  • 类型名称应该是程序集限定,类似于"System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";请注意,版本和公钥可能会有所不同 `

标签: c# winforms reflection properties


【解决方案1】:

首先,你需要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);  

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

 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, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

MessageBox.Show(t.Name);
  

【讨论】:

  • 这正是我想要的。谢谢。
  • 如果我有类似 string mybuttonname = "button1"; Type t = Type.GetType( @"System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); PropertyInfo prop = t.GetProperty("Enabled"); if (null != prop &amp;&amp; prop.CanWrite &amp;&amp; prop.Name.Equals("Enabled")) { prop.SetValue((object)mybuttonname, "False", null); } 的东西,我会收到错误 System.Reflection.TargetException: 'Object does not match target type.'在这种情况下如何指向特定按钮?
  • 您必须找到该实例,即从其名称中获取button1 ("button1");你可以输入object instance = myForm.Controls.Find("button1", true);。请注意,"False" 的类型为string,这就是不正确的原因;它应该是 false 类型的 bool
  • 如果我知道控件名称和类型,还有其他方法可以避免找到控件吗?问题是,例如,如果我有工具栏按钮控件,那么我无法在表单上轻松找到控件。我正在寻找以某种方式指向使用控件名称进行控制...我不知道这在 C# 中是否可行。
  • 好吧,ToolBarButton 不是Control 类型,而只是Component;这就是为什么我们必须以不同的方式进行搜索;您可以枚举所有ToolBar 并分析他们的Buttons 集合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
相关资源
最近更新 更多