2009-11-29 22 views
0

其實我需要4個methodes。我正在使用C#.NET 3.5和Windows窗體。如何獲得控件屬性,然後將它們保存到XML並加載它?

  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 

此方法不返回所有控件的屬性和我不知道爲什麼。

步驟4:

//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 reults迭代。

請幫我解決這些問題。

感謝和問候。

回答

3

您是否知道使用Windows Forms可以使用現有設置基礎結構來保存控件和表單的設置?從設計器中選擇一個控件,然後在「應用程序設置」和屬性綁定下的屬性中,可以將控件上的任何屬性綁定到將生成的屬性,以訪問並保存該屬性值。這些設置可以是應用程序或用戶範圍。這些設置還將使用獨立存儲,允許您升級到不同版本的設置以保持版本之間的用戶設置以及許多其他功能。所以這可能不會直接回答您的問題,但可能是針對您的特定問題的更好解決方案。一旦你綁定一個屬性,你可以隨時保存更改,在每個用戶或每個應用程序的基礎上,如下所示:

Settings.Default.TextBox1 = textBox2.Text; Settings.Default.BackColor = Color.Blue; Settings.Default.Save();

+0

首先感謝您的回答。是的,我知道這個解決方案,但這不是我需要的。 – Jooj 2009-11-29 19:48:16

+0

如果它不是你所需要的,爲什麼要接受答案? – 2015-04-28 21:11:37

相關問題