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

前端 未结 7 1130
执笔经年
执笔经年 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条回答
  •  日久生厌
    2020-11-28 23:11

    Thank for the question. But I have found my own solution to this problem. At first, I created a method

        public T GetSettingsWithDictionary() where T:new()
        {
            IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
            .AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
    
            var instance = new T();
            foreach (var property in typeof(T).GetProperties())
            {
                if (property.PropertyType == typeof(Dictionary))
                {
                    property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get>());
                    break;
                }
    
            }
            return instance;
        }
    

    Then I used this method to produce an instance of a class

    var connStrs = GetSettingsWithDictionary();
    

    I have the next declaration of class

    public class AuthMongoConnectionStrings
    {
        public Dictionary ConnectionStrings { get; set; }
    }
    

    and I store my setting in App.config

        
      
     
    

提交回复
热议问题