Save window size & position in WPF

* Right Click on Settings.settings and Open With XML (Text) Editor

* Add Top, Left, Height, Width & WindowState settings

<Settings>
  <Setting Name="Top" Type="System.Double" Scope="User">
    <Value Profile="(Default)">50</Value>
  </Setting>
  <Setting Name="Left" Type="System.Double" Scope="User">
    <Value Profile="(Default)">50</Value>
  </Setting>
  <Setting Name="Height" Type="System.Double" Scope="User">
    <Value Profile="(Default)">800</Value>
  </Setting>
  <Setting Name="Width" Type="System.Double" Scope="User">
    <Value Profile="(Default)">1200</Value>
  </Setting>
  <Setting Name="WindowState" Type="System.Windows.WindowState" Scope="User">
    <Value Profile="(Default)">Normal</Value>
  </Setting>
</Settings>
* Add Settings property to App.xml
<Application.Resources>
    <properties:Settings x:Key="Settings" />
</Application.Resources>
* Add OnExit override to persist the settings when exiting application
protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    Settings.Default.Save();
}
* Add Top, Left, Height, Width & WindowState bindings to your MainWindow
<Window x:Class="TestApp.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow"
  Top="{Binding Source={StaticResource Settings}, Path=Default.Top, Mode=TwoWay}"
  Left="{Binding Source={StaticResource Settings}, Path=Default.Left, Mode=TwoWay}"
  Width="{Binding Source={StaticResource Settings}, Path=Default.Width, Mode=TwoWay}"
  Height="{Binding Source={StaticResource Settings}, Path=Default.Height, Mode=TwoWay}"
  WindowState="{Binding Source={StaticResource Settings}, Path=Default.WindowState}">

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#