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?
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:settings="clr-namespace:WpfApplication1.Properties"
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}">
<Grid>
</Grid>
</Window>
The settings look like this:
And to persist, I'm simply using the following code:
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
}
And here is an example for WPF VB.NET
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:Properties="clr-namespace:WpfApplication1"
Title="Test"
Loaded="Window_Loaded" Closing="Window_Closing"
Height="{Binding Height, Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Width="{Binding Width,Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Left="{Binding Left,Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Top="{Binding Top, Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
>
<Grid Name="MainFormGrid"> ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With