Sunday, October 26, 2014

Cannot access Properties.Settings from App.xaml.vb

I don't generally like the Settings class in the .Net framework because it does not work well with ClickOnce deployment. If you alter the settings collection between deployments, the new deployment thinks the users' settings files are corrupt and refuses to run until you destroy them. This pretty much renders settings useless.

However I noticed another problem the other day while messing around. Let's pretend your project has a setting of "Name" defined as a string with user scope. To access this setting in the main window you would use...

String Name;
Name = Properties.Settings.Default.Name;

Now try the same thing in App.xaml.vb and the compiler will complain that Settings is not valid.


The clue is buried in the error message. It's expecting a dictionary. What's happening here is that the compiler is confusing Properties.Settings with Application.Current.Properties(...) and it's expecting a dictionary key (or some dictionary reference) to follow "Properties".

To reference the settings from the App.xaml.vb you need to explicitly prefix "Properties" with the default namespace ie.

String Name;
Name = Lesson_2.Properties.Settings.Default.Name;

The best approach would be to always use the fully qualified reference for both Properties.Settings and Application.Current.Properties ie.

String Name;
Name = Lesson_2.Properties.Settings.Default.Name;
Application.Current.Properties["Name"] = Name;

Of course, Visual Basic uses the My syntax to access settings which avoids this confusion completely.


No comments:

Post a Comment