繁体   English   中英

如何获取控件属性,然后将其保存到XML并重新加载?

[英]How to get control properties then save them to XML and load it back?

实际上,我将需要4种方法。 我正在使用c#.NET 3.5和Windows窗体。

  1. 从名称与列表名称匹配的当前表单中获取所有控件属性(以及子菜单项,例如MenuItems等)//无效
  2. 将结果保存为XML //不知道如何保存结果
  3. 从XML加载结果
  4. 最后从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结果。

您能帮我解决这些问题吗?

谢谢,最好的问候。

您是否知道Windows窗体具有现有的设置基础结构,可用于保存控件和窗体的设置? 从设计器中,选择一个控件,然后在“应用程序设置”下的属性中,然后选择“属性绑定”,可以将控件上的任何属性绑定到将要生成的属性,以访问和保存该属性值。 这些设置可以是应用程序范围或用户范围的。 这些设置还将使用隔离存储,使您可以升级到不同版本的设置,以维护版本之间的用户设置以及许多其他功能。 因此,这可能不会直接回答您的问题,但可能是针对您特定问题的更好解决方案。 绑定属性后,您可以随时基于每个用户或每个应用程序保存更改,如下所示:

Settings.Default.TextBox1 = textBox2.Text; Settings.Default.BackColor =颜色。蓝色; Settings.Default.Save();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM