【问题标题】:How to get control properties then save them to XML and load it back?如何获取控件属性,然后将它们保存到 XML 并重新加载?
【发布时间】:2009-11-29 15:55:40
【问题描述】:

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

  1. 从名称与列表名称匹配的当前表单中获取所有控件属性(还有子属性,如 MenuItems 等)//不起作用
  2. 将结果保存到 XML //不知道如何保存结果
  3. 从 XML 和
  4. 加载结果
  5. 最终从 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


    【解决方案1】:

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

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

    【讨论】:

    • 首先感谢您的回答。是的,我知道这个解决方案,但这不是我需要的。
    猜你喜欢
    • 2012-08-10
    • 2020-05-10
    • 2022-10-16
    • 2016-03-24
    • 2014-03-04
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多