Welcome to WindowsClient.net | Sign in | Join
in

WindowsClient.net

This Blog

Syndication

Sponsors





Tags

No tags have been created or used yet.

Archives

Bragi

July 2008 - Posts

  • Using settings in WPF (or how to store/retrieve window pos and loc)

    One of those questions that comes up once and a while on the MSDN forum is how to properly use the project settings (that you can easily define in the VS designer) from xaml. A common situation is to store and retrieve the location and size of the main window at startup and closing of the app. This can all be done from xaml using bindings without having to write a line of code (actually, that's not entirely true, you still need 1 line). Here's a small example:

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:self="clr-namespace:JaStDev.CQuenze"
            x:Class="JaStDev.CQuenze.Window1"
            Title="CQuenze" 
            Height="{Binding Source={x:Static self:Properties.Settings.Default}, 
                             Path=ApplicationHeight, Mode=TwoWay}"
            Width="{Binding Source={x:Static self:Properties.Settings.Default}, 
                            Path=ApplicationWidth, Mode=TwoWay}"
            Top ="{Binding Source={x:Static self:Properties.Settings.Default}, 
                           Path=ApplicationTop, Mode=TwoWay}"
            Left ="{Binding Source={x:Static self:Properties.Settings.Default}, 
                            Path=ApplicationLeft, Mode=TwoWay}"
            WindowState="{Binding Source={x:Static self:Properties.Settings.Default}, 
                                  Path=ApplicationWindowState, Mode=TwoWay}">

    The basic idea is very simple.  I have created 5 setting entries called ApplicationWidth, ApplicationHeight, ApplicationTop, ApplicationLeft (all doubles) and ApplicationWindowState (System.Windows.WindowState). Since the settings can be reached in code through properties on a static class (Properties.Settings.Default), you can also bind to them using Source={x:Static self:Properties.Settings.Default}. Also notice that I have declared Mode=TwoWay on all bindings to make certain that changes to the position of the main window are automatically stored in the settings.

    And finally, we need to save the settings to disk when the user closes the application.  This is done by with the following statement:

    Properties.Settings.Default.Save();

    Usually, you call this in the event handler for the Window.Closed or Application.Exit event. This depends on your taste and the way you close your application. Personally, I find the Application.Exit the most appropriate.

Page view counter