2

In my WPF MVVM application, I have Model, View, and ViewModel as a separate projects. Now, in my View application I have user settings defined in Settings.settings file, I can access them through:

Properties.Settings.Default.MySettingName

and in my Tool.exe.xml I can confirm that the setting is there:

<userSettings>
    <Tool.Properties.Settings>
        <setting name="MySettingName" serializeAs="String">
            <value>False</value>
        </setting>
    </Tool.Properties.Settings>
</userSettings>

Now the question is how do I access those settings from my ViewModel project? It's obvious that if I were to do Properties.Settings.Default.* it will point to it's own settings.

So far I tried to do the following two ways:

Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = configFile.AppSettings.Settings;

and

var keys = ConfigurationManager.AppSettings.AllKeys;

But both of them always return 0 entities.

I also know that I can create a ViewModel and bind settings from the View, but for this particular case, creating a new ViewModel just to access setings sounds a little bit overkill.

Thanks for help!

inside
  • 3,047
  • 10
  • 49
  • 75
  • If you are using visual studio you can change the access modifier for the settings class to public. Double click the Settings.settings file and there is a drop down at the top. You can then access the settings using the full namespace – user2697817 Apr 21 '15 at 13:28
  • A better way would be to provide a service that wraps the settings using `SettingsBase` – user2697817 Apr 21 '15 at 13:31
  • Can you give a bit more details on a service? – inside Apr 21 '15 at 13:33

2 Answers2

2

Thanks to the https://stackoverflow.com/a/632161/1729349

Here's how I was able to access the value of the setting:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// find section
ClientSettingsSection configSection = config.SectionGroups[@"userSettings"].Sections["Tool.Properties.Settings"] as ClientSettingsSection;

var setting = configSection.Settings.Get("MySettingName").Value.ValueXml.InnerText;
Community
  • 1
  • 1
inside
  • 3,047
  • 10
  • 49
  • 75
0

AppSettings is for the 'default' appSettings configuration section. You need to open your own configuration section. Try this:

ConfigurationManager.GetSection("userSettings");
James Lucas
  • 2,452
  • 10
  • 15