【发布时间】:2025-12-23 19:50:06
【问题描述】:
我目前正在编写一个允许我自定义表单元素的库。下面的代码是一个函数,它获取控件的名称,获取属性的名称,然后设置控件的属性,但由于某种原因我似乎无法让它工作。感谢任何帮助。
代码:
public void SetProp(string name, string prop, string value)
{
Form FormControl = Application.OpenForms[form];
Control mycontrol = FormControl.Controls.Find(name, true)[0];
PropertyInfo pInfo = mycontrol.GetType().GetProperty(prop);
TypeConverter tc = TypeDescriptor.GetConverter(pInfo.PropertyType);
var x = tc.ConvertFromString(value);
pInfo.SetValue(name, x, null);
}
示例调用:
SetProp("greg", "Text", "hi")
【问题讨论】:
-
pInfo.SetValue()看起来不对。你应该传入mycontrol,而不是name。试试pInfo.SetValue(mycontrol, x);。 -
@TyCobb 是的,解决了这个问题。非常感谢!
标签: c# winforms properties controls