简体   繁体   中英

Read Properties.Settings.Default from a different project

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!

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;

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

ConfigurationManager.GetSection("userSettings");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM