Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
Maxim Gershkovich Avatar asked Nov 29 '22 17:11

Maxim Gershkovich


2 Answers

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:

Settings file

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

void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Properties.Settings.Default.Save();
}
like image 100
madd0 Avatar answered Dec 24 '22 19:12

madd0


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"> ...
like image 24
Sam Avatar answered Dec 24 '22 20:12

Sam