BrownBot Logo BrownBot Head

Handling application close from a user control in WPF

12:41 am Filed under: Uncategorized

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 Comment »

  1. […] BrownBot: Handling application close from a user control in WPF […]

    Pingback by WPF/Silverlight/XAML Web News - 2008/05/09 - Rob Relyea - Xamlified — May 9, 2008 @ 9:59 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.

Powered by WordPress