Search code examples
c#silverlightxamlwindows-desktop-gadgets

Retaining values in Silverlight App on exit


Just as it says in the title of this question, I am trying to retain a Timespan value when the application is closed. Here's the situation...I am writing a Windows gadget, everytime the flyout window is closed it destroys it, and the Timespan value along with it. I want it so each time the flyout window is closed it retains this value how would this be accomplished?

The code of what I'm currently doing is below.

SilverlightGadgetUtilities.Stopwatch watch = new SilverlightGadgetUtilities.Stopwatch();

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        watch.currentTime();
        this.RootVisual = new Page();

    }

    private void Application_Exit(object sender, EventArgs e)
    {

        watch.currentTime();
    }

And this is in my Stopwatch class:

    public TimeSpan? currentTime()
    {
        current = Elapsed;
        return current;
    }

    public TimeSpan? Elapsed
    {
        get
        {
            return new TimeSpan(this.GetElapsedDateTimeTicks() * 10000000);
        }
    }

Where GetElapsedDateTimeTicks() is using DateTime.Now.Second() for the timing.

Thanks again!


Solution

  • You can store data in your application's isolated storage settings and retrieve it on launch.

    Here is an example of storing the information in IsolatedStorageSettings:

    IsolatedStorageSettings.ApplicationSettings.Add("MySettingName", MySetting);
    

    You would then retrieve it using:

    IsolatedStorageSettings.ApplicationSettings["MySettingName"];
    

    IsolatedStorageSettings.ApplicationSettings acts very much like a dictionary. You should check to see if there is already a setting of that name being stored, and if so, either remove it, or overwrite it. Overwriting it could be done like so:

    if (!IsolatedStorageSettings.ApplicationSettings.Contains("MySettingName"))
        IsolatedStorageSettings.ApplicationSettings.Add("MySettingName", MySetting);
    else
        IsolatedStorageSettings.ApplicationSettings["MySettingName"] = MySetting;
    

    The code to remove and re-add would be similar, except swapping the else block for:

    else
    {
        IsolatedStorageSettings.ApplicationSettings.Remove("MySettingName");
        IsolatedStorageSettings.ApplicationSettings.Add("MySettingName", MySetting);
    }