Handling application close from a user control in WPF

Struck this one the other day and didn’t find a decent answer so here’s my solution.

I’ve got a user control or class that I want to have save one of it’s properties to the Settings.Settings on application shut down.  First thing you’ll find on a user control is that it doesn’t have an OnClose() or OnDispose() to override, lucky for us there’s an Exit event in Appliction.Current that we can subscribe to in our constructor instead.

He’s what it looks like…

public class ScheduleBuilder : INotifyPropertyChanged
{
    public ScheduleBuilder()
    {
        DetailWidth = Properties.Settings.Default.PreProdSchedDetailWidth;

        Application.Current.Exit += new ExitEventHandler(OnApplicationExit);
    }

    private int _detailWidth;

    public int DetailWidth
    {
        get
        {
            return _detailWidth;
        }
        set
        {
            if (value != _detailWidth)
            {
                _detailWidth = value;
                OnPropertyChanged("DetailWidth");
            }
        }
    }

    void OnApplicationExit(object sender, ExitEventArgs e)
    {
        Properties.Settings.Default.PreProdSchedDetailWidth = _detailWidth;
        Properties.Settings.Default.Save();
    }
}

One word of warning, be carefully doing this if you plan you use multiple instances of the class/control, you wont know which one will be that last one to save it’s value.

1 thought on “Handling application close from a user control in WPF

  1. Pingback: WPF/Silverlight/XAML Web News - 2008/05/09 - Rob Relyea - Xamlified

Leave a Reply

Your email address will not be published. Required fields are marked *