Click here to Skip to main content
Click here to Skip to main content

Save and Restore the Location, Position and State of a WPF Window.

, 11 Oct 2006
Rate this:
Please Sign up or sign in to vote.
Presents a class that persists a WPF Window's state data using attached properties.

Introduction

I like the main window of my applications to "remember" its position, size and state. I want a no fuss method to add this functionality to my projects.

This article presents a class that provides this functionality using attached properties. The attached properties method provides a solution that does not involve subclassing the window. This solution does not require any code to be placed in the windows "code behind" file, hence keeping good separation of presentation and business layers. My solution is applied to my WPF project with the addition of a couple of lines of XAML.

This code was written and tested against the June 2006 CTP of the .NET Framework 3.0.

Using the code

One of the goals of the code is that it is easy to use. Because of this, I am going to start off by explaining how to use it and then follow up by explaining how it works.

  1. Create a new WinFX Windows Application with Visual Studio 2005 and add a reference to the Kingsmill.Windows.dll assembly.
  2. Open Window1.xaml and view the XAML; it should look like this:
    <Window x:Class="WindowsApplication1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="WindowsApplication1 "Height="300" Width="300">
        <Grid>
        </Grid>
    </Window>
    
  3. Edit Window1.xaml as per the following:

    <Window x:Class="WindowsApplication1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:k="http://schemas.kingsmill.com/kingsmill/windows"
            Title="WindowsApplication1 "Height="300" Width="300"
            k:WindowSettings.Save="True">
        <Grid>
        </Grid>
    </Window>
    
  4. Run and stop the application, resizing and repositioning the window a few times. Note that the window size position and state is now "remembered".

How it works

The solution is implemented within the WindowSettings class.

What we are doing here is adding some behavior to the Avalon Window by adding some event handlers, but without subclassing the Window. The Avalon property system allows us to register a property that can be attached to any element; in our case the Window element. This is the same mechanism that allows us to put XAML code like DockPanel.Dock="Top" on a Button inside a DockPanel, even though Dock isn't a property that buttons know about. We can also make use of the ability to register for a callback when the property changes.

Here is our code that registers the Save property and registers the OnSaveInvalidated callback that is executed when the Save property value is changed.

/// <summary>
/// Register the "Save" attached property and the "OnSaveInvalidated" callback
/// </summary>
public static readonly DependencyProperty SaveProperty
    = DependencyProperty.RegisterAttached("Save", typeof(bool), 
    typeof(WindowSettings), new FrameworkPropertyMetadata
        (new PropertyChangedCallback(OnSaveInvalidated)));

and here is the callback:

/// <summary>
/// Called when Save is changed on an object.
/// </summary>
private static void OnSaveInvalidated(DependencyObject 
    dependencyObject, DependencyPropertyChangedEventArgs e)
{
    Window window = dependencyObject as Window;
    if (window != null)
    {
        if ((bool)e.NewValue)
        {
            WindowSettings settings = new WindowSettings(window);
            settings.Attach();
        }
    }
}

The method above is called in response to our XAML line:

k:WindowSettings.Save="True"

Examining the OnSaveInvalidated method, we see that the dependencyObject is a Window, e.NewValue = true and a new WindowSettings object is created that wraps our Window. The Attach() method is then called which attaches our desired Load and Save behavior to the Avalon Window by attaching some event handlers whose responsibility it is to call the LoadWindowState() and SaveWindowState() methods when the Window is initialized and closed.

Well, that's about all there is to it. The rest of the code deals with saving and loading the settings and that has been discussed in other articles and is nothing new.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

TimK
Web Developer
Australia Australia
No Biography provided

Comments and Discussions

 
QuestionMultiple Monitors, but remoting in on a single monitor Pinmemberopenshac15-Apr-13 4:30 
GeneralUpdate fixing bug with multiple monitors PinmemberHeinz JKarl Otta Fritz8-Jan-11 4:09 
GeneralPersistId is obsolete PinmemberPhil J Pearson20-Nov-09 6:53 
GeneralThe attachable property 'Save' was not found in type 'WindowSettings' PinmemberChuck14114-Jun-09 11:46 
GeneralMultiple windows PinmemberStrattonN15-May-09 9:08 
GeneralRe: Multiple windows Pinmemberehuna4-Jun-09 10:02 
AnswerRe: Multiple windows Pinmembersuper-e-28-Oct-10 2:04 
QuestionWhere does this save the settings? Pinmemberjwhurst21-Jan-08 14:11 
GeneralRe: Where does this save the settings? PinmemberMember 321449827-Apr-08 17:54 
AnswerRe: Where does this save the settings? PinmemberJani Giannoudis10-May-08 23:20 
GeneralError (Using Orcas Beta1) Pinmembernoirs213-Aug-07 8:11 
QuestionHow does I get this window's attached property in Expression Blend PinmemberK Joy15-May-07 21:59 
GeneralSmall bug fix for maximizing windows PinmemberErwyn7419-Dec-06 4:50 
GeneralWorks in .NET 3.0 RTM PinmemberErwyn7419-Dec-06 4:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 11 Oct 2006
Article Copyright 2006 by TimK
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid