Maxim Gershkovich Maxim Gershkovich - 1 year ago 254
C# Question

WPF window location binding

In windows forms there was an option in the properties section of a form to establish a binding between an application setting and the windows form.

Typically I would end up with a setting called frmMyFormName_Location this was then automagically updated as required and all I needed to do was call the Settings.Save() method on application exit to persist location.

Could someone please provide an example of the same thing in WPF as I have been unable to work out how to accomplish this?

Answer Source

It's extremely simple to bind to user or application settings from a .settings file in WPF.

Here's an example of a window that gets its position and size from settings:

<Window x:Class="WpfApplication1.MainWindow"
        Height="{Binding Height, Source={x:Static settings:Settings.Default}, Mode=TwoWay}" 
        Width="{Binding Width, Source={x:Static settings:Settings.Default}, Mode=TwoWay}"
        Top="{Binding Top, Source={x:Static settings:Settings.Default}, Mode=TwoWay}"
        Left="{Binding Left, Source={x:Static settings:Settings.Default}, Mode=TwoWay}">


The settings look like this:

Settings file

And to persist, I'm simply using the following code:

void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download