2009-08-10 46 views

回答

1

有Windows窗體中一個標籤屬性,但它不堅持。

我使用的模式是創建一個類調用預置(對每一條信息我要堅持屬性),然後用PreferencesManager類進行管理,像這樣的:

public class PreferencesManager 
{ 
    static private string dataPath = null; 
    static public string DataPath 
    { 
     get 
     { 
      if (dataPath == null) 
      { 
       string baseFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); 
       dataPath = Path.Combine(baseFolder, @"MY_APP_NAME"); 

       if (!Directory.Exists(dataPath)) 
       { 
        Directory.CreateDirectory(dataPath); 
       } 
      } 

      return dataPath; 
     } 
    } 

    /// <summary> 
    /// Saves the specified preferences. 
    /// </summary> 
    /// <param name="pref">The preferences.</param> 
    static public void Save(Preferences pref) 
    { 
     // Create file to save the data to 

     string fn = "Preferences.xml"; 
     string path = Path.Combine(DataPath, fn); 
     using (FileStream fs = new FileStream(path, FileMode.Create)) 
     { 

      // Create an XmlSerializer object to perform the serialization 
      XmlSerializer xs = new XmlSerializer(typeof(Preferences)); 

      // Use the XmlSerializer object to serialize the data to the file 
      xs.Serialize(fs, pref); 
     } 
    } 

    static public Preferences Load() 
    { 
     Preferences ret = null; 
     string path = string.Empty; 

     try 
     { 
      // Open file to read the data from 

      string fn = "Preferences.xml"; 
      path = Path.Combine(DataPath, fn); 
      using (FileStream fs = new FileStream(path, FileMode.Open)) 
      { 

       // Create an XmlSerializer object to perform the deserialization 
       XmlSerializer xs = new XmlSerializer(typeof(Preferences)); 

       // Use the XmlSerializer object to deserialize the data from the file 
       ret = (Preferences)xs.Deserialize(fs); 
      } 
     } 
     catch (System.IO.DirectoryNotFoundException) 
     { 
      throw new Exception("Could not find the data directory '" + DataPath + "'"); 
     } 
     catch (InvalidOperationException) 
     { 
      return new Preferences(); 
     } 
     catch (System.IO.FileNotFoundException) 
     { 
      return new Preferences(); 
     } 

     return ret; 
    } 

} 
+0

哇,非常感謝代碼片段:) – programmernovice 2009-08-10 21:12:28

3

.NET中的大多數UI控件都有一個.Tag屬性,可用於同一目的。

但是,如果你需要額外的功能,可以使一類從基本控制(即你可以創建一個名爲SpecialPictureBox類,從繼承的PictureBox,並增加了額外的字段),並使用繼承它在你的Windows窗體中就像你可以使用PictureBox一樣。

+0

除非我m錯誤了,.Tag沒有被持續 – 2009-08-10 20:46:42

+0

。標籤也沒有在VB6中持久。 ;) – Brandon 2009-08-11 03:06:46

相關問題