2017-06-07 240 views
0

在我的WPF應用程序中,我有Properties.Settings.Default.Something訪問的設置。 在這些用戶設置中,我保存了不同的文本框,單選按鈕,複選框值。 我需要根據一個組合框的選擇來設置這些設置,並保存它。例如,用戶在組合框中選擇「1」,在文本框中設置文本,選擇2,再次在文本框中設置文本。重新打開應用程序後,我希望保存這些文本框的值。組合框選項的內容是動態生成的。WPF如何創建,保存和加載多個設置文件

我知道這些設置保存在位於用戶/應用程序數據的配置文件/ ...但我不知道如何,如果它甚至有可能使多個文件這樣的手動保存並加載運行。

回答

0

將它們序列化爲xml文件。這是一個通用的例子,如何做到這一點。 請檢查DataContracthere

C#

private static T ReadXmlFile<T>(string path) where T : class 
    { 

     T result = null; 
      if (File.Exists(path)) 
      { 

       try 
       { 
        using (XmlReader reader = XmlReader.Create(path)) 
        { 
         DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
         result = (T)serializer.ReadObject(reader); 
        } 
       } 
       catch (Exception ex) 
       { 
        throw ex; // or what ever 
       } 
      } 
      return result; 
     } 

    private static void WriteXmlFile<T>(string path, T content2write) where T : class 
    { 
     if (!Directory.Exists(Path.GetDirectoryName(path))) 
     { 
      Directory.CreateDirectory(Path.GetDirectoryName(path)); 
     } 


     using (XmlWriter writer = XmlWriter.Create(path, 
                new XmlWriterSettings 
                { 
                 Indent = true, 
                 IndentChars = " ", 
                 Encoding = Encoding.UTF8, 
                 CloseOutput = true 
                })) 
     { 
      DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
      serializer.WriteObject(writer, content2write); 
     } 
    } 

也許將它們保存在自己的AppData -folder與Environment.SpecialFolder.LocalApplicationData ;-)去這樣

private static readonly string MyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"MyApp\AppDescription");