2017-06-07 235 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");