Binding to a Settings file

Something that I find really cool is that you can bind directly to a user settings file in wpf. In the example below I've bound a toggle button to a user setting in a settings file. Toggling the button will update the settings file with 0 code!

<ToggleButton x:Name="btnNetworkSpeed" Margin="5,0,0,0" FlowDirection="LeftToRight" IsChecked="{Binding Source={x:Static InfrastructureProperties:Settings.Default}, Path=IsSlowConnectionSpeed, Mode=TwoWay}" FontSize="9"/>

The trick to making this work is to change the settings file access modifier to Public. To do this go into the settings file and at the top of the designer there is a drop down. What this does under the covers is change the compile tool from 'SettingsSingleFileGenerator' to 'PublicSettingsSingleFileGenerator'

If you want the setting to be persisted on the closing event of the application add this line and you're done.

protected override void OnExit(ExitEventArgs e)
{
Modules.Infrastructure.Properties.Settings.Default.Save();
...
}

No comments:

Post a Comment