How to get a List collection of values from app.config in WPF?

前端 未结 7 1116
执笔经年
执笔经年 2020-11-28 22:42

The following example fills the ItemsControl with a List of BackupDirectories which I get from code.

How can I change this

7条回答
  •  -上瘾入骨i
    2020-11-28 23:27

    There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection (as in Richard's answer) and parsing the string yourself (as in Adam's answer).

    For example, you could write the following configuration section:

    public class MySection : ConfigurationSection
    {
        [ConfigurationProperty("MyStrings")]
        [TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
        public CommaDelimitedStringCollection MyStrings
        {
            get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
        }
    }
    

    You could then have an app.config that looks like this:

    
    
      
        

    Finally, your code would look like this:

    var section = (MySection)ConfigurationManager.GetSection("foo");
    foreach (var s in section.MyStrings)
        Console.WriteLine(s); //for example
    

提交回复
热议问题