Home > front end >  How can I bind user settings (Properties.Settings.Default) to WPF controls?
How can I bind user settings (Properties.Settings.Default) to WPF controls?

Time:04-24

I want to create a WPF window for user settings, and bind the controls to the user settings which are defined in Properties.Settings.Default. Sounds pretty straight forward, like something that's done in almost all apps. However it seems I cannot achieve a bi-directional binding, i.e. the controls show the values, but the user input is not written back into the settings object. Here's part of the XAML with a canvas which defines a data context and contains some controls.

<Canvas x:Name="CanvasMain">
    <Canvas.DataContext>
        <Properties:Settings/>
    </Canvas.DataContext>
    <CheckBox x:Name="chkThingEnabled" Content="Thing" Height="20" Canvas.Left="19" Canvas.Top="64" Width="106" IsChecked="{Binding ThingEnabled}"/>
    <TextBox Canvas.Left="19" Text="{Binding TestText}" Canvas.Top="104" Width="120"/>
</Canvas>

The settings are simply entered in the default settings grid of the project: ThingEnabled: Type = bool, Scope = User, Value = False TestText: Type = string, Scope = User, Value = "TEST"

How can I make this data binding, so the changes to the control values are written into the bound properties of the settings?

CodePudding user response:

An expression like

<Properties:Settings/>

would create a new instance of the Settings class.

In order to bind to the static Default property of the Settings class in the namespace YourApplication.Properties you would need a proper XAML namespace declaration and an appropriate Binding expression with the static property path in parentheses.

You should also consider using a suitable layout Panel. Canvas is not the right thing here.

Something like this should work:

<Window ...
    xmlns:properties="clr-namespace:YourApplication.Properties">

    <StackPanel DataContext="{Binding Path=(properties:Settings.Default)}">

        <CheckBox IsChecked="{Binding ThingEnabled}" .../>
        <TextBox Text="{Binding TestText}" .../>
    </StackPanel>
</Window>

CodePudding user response:

You need to call Properties.Settings.Default.Save() method to make the settings persistent sometime before closing your app. See How To: Write User Settings at Run Time with C#.

In practice, this approach is not so convenient because the path of user settings file is dependent on the version number of your app and it will not be passed to newer version if you update the version.

  • Related