【发布时间】:2009-11-29 15:55:40
【问题描述】:
实际上我需要 4 种方法。我正在使用 c# .NET 3.5 和 windows 窗体。
- 从名称与列表名称匹配的当前表单中获取所有控件属性(还有子属性,如 MenuItems 等)//不起作用
- 将结果保存到 XML //不知道如何保存结果
- 从 XML 和 加载结果
- 最终从 XML 设置加载的控件属性。 //很好用
现在我正在执行此表单的第 1 步:
public static Dictionary<string, object> xmlDictionary;
public Control FindControlRecursive(Control container, List<string> properties)
{
foreach (Control controls in container.Controls)
{
Type controlType = controls.GetType();
PropertyInfo[] propertyInfos = controlType.GetProperties();
foreach (PropertyInfo controlProperty in propertyInfos)
{
foreach (string propertyName in properties)
{
if (controlProperty.Name == propertyName)
{
xmlDictionary.Add(controlProperty.Name, controlProperty.GetValue(controls, null));
}
}
}
Control foundCtrl = FindControlRecursive(controls, properties);
if (foundCtrl != null)
return foundCtrl;
}
return null;
}
调用方法:
List<string> propertyNames = new List<string>(); //list of all property names I want to save
propertyNames.Add("Name");
propertyNames.Add("Text");
propertyNames.Add("Size");
FindControlRecursive(this, propertyNames); //this is the current form
这个方法没有返回所有控件属性,我不知道为什么。
第四步:
//field = some new field
//newValue = new value
FieldInfo controlField = form.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
object control = controlField.GetValue(form);
PropertyInfo property = control.GetType().GetProperty(newValue);
property.SetValue(control, items.Value, new object[0]);
第 4 步效果很好,但不知道如何遍历 XML 结果。
你能帮我解决这些问题吗?
感谢和最好的问候。
【问题讨论】:
标签: c# .net xml winforms reflection