包括控件位置、颜色等等所有属性,导出为xml,能直接导出所有属性吗?还是只能一个属性一个属性的写入xml?
struct ControlPro
{
public string ControlType;
public string ControlName;
public string ProName;
public string ProValue;
}
private void ucMain_Load(object sender, EventArgs e)
{
PropertyInfo[] allPros = GetPropertyInfoArray();
List<ControlPro> list = new List<ControlPro>();
foreach (Control control in this.panel2.Controls)
{
if (control is Buttonx)
{
ControlPro p = new ControlPro();
foreach (PropertyInfo pro in allPros)
{
if (pro.Name.StartsWith("_"))
{
object proValue = pro.GetValue(control, null);
if (proValue is String)
{
p.ControlType = control.GetType().Name;
p.ControlName = control.Name;
p.ProName = pro.Name;
p.ProValue = proValue.ToString();
list.Add(p);
}
else if (proValue is Color)
{
Color color = (Color)proValue;
p.ControlType = control.GetType().Name;
p.ControlName = control.Name;
p.ProName = pro.Name;
p.ProValue = color.A + "," + color.R + "," + color.G + "," + color.B;
list.Add(p);
}
else if (proValue is Point)
{
Point point = (Point)proValue;
p.ControlType = control.GetType().Name;
p.ControlName = control.Name;
p.ProName = pro.Name;
p.ProValue = point.X + "," + point.Y;
list.Add(p);
}
else if (proValue is Size)
{
Size size = (Size)proValue;
p.ControlType = control.GetType().Name;
p.ControlName = control.Name;
p.ProName = pro.Name;
p.ProValue = size.Width + "," + size.Height;
list.Add(p);
}
}
}
}
}
DataTable dt = list.CopyToDataTable(); //https://blog.csdn.net/weixin_30699741/article/details/97942941
dt.WriteXml("d:\\21121.xml");
}
private PropertyInfo[] GetPropertyInfoArray()
{
PropertyInfo[] props = null;
try
{
Type type = typeof(Buttonx);
object obj = Activator.CreateInstance(type);
props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
catch (Exception ex)
{ }
return props;
}
public class ControlAttribute
{
public string name;
public object value;
public ControlAttribute(string n,object o)
{
name = n;
value = o;
}
}
public static List<ControlAttribute> controlAttributes = new List<ControlAttribute>();
public class AllControl
{
public List<ControlAttribute> controls = new List<ControlAttribute>();
public AllControl(List<ControlAttribute> c)
{
controls = c;
}
}
public static List<AllControl> allControls = new List<AllControl>();
public static void ForeachClassProperties<T>(T model)
{
Type t = model.GetType();
PropertyInfo[] PropertyList = t.GetProperties();
foreach (PropertyInfo item in PropertyList)
{
controlAttributes.Add(new ControlAttribute(item.Name, item.GetValue(model, null)));
}
}
private void ucMain_Load(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
controlAttributes.Clear();
ForeachClassProperties(control);
allControls.Add(new AllControl(controlAttributes));
}
}
思路:2个步骤,1.遍历你要保存的控件属性;2.将遍历的属性按照格式写入xml
那还不是得一个属性一个属性的写入xml,属性太多了,懒得写了
如果自己做模板基类,还是手写,也就是反射好一些,保存可写可读的属性,手工写在中间过程中可以筛选。如www.99dxz.com窗体位置,毕竟当启动按自动模式时,窗口会自动差叠排列,如窗口多,还是手写保险些,前面费时间,后面效果好。
我其实有个比较好的方案。
就是保存designer.cs文件。
具体保存文件,还是里面的代码,这个你随意。