Lotzi11
Lotzi11

Reputation: 549

Storing Variables in UWP C#

I've been writing Universal Windows Apps for over a month now, and I wanted to make sure that I was storing variables I want to use throughout the entire app in the appropriate place. What I have been doing is placing variables in App.xaml.cs and creating an App variable that references the current app as follows

private App obj = (App)App.Current;

I am then able to grab the variables that I sotre in App.xaml.cs and use it when needed. Is this a correct way of storing information or is there a better way of storing these variables?

Upvotes: 0

Views: 1770

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

Per your description, I think what you need is ApplicationData.LocalSettings, take a look at Store and retrieve settings and other app data.

Code will be like the following

Create a setting

Windows.Storage.ApplicationDataCompositeValue composite = 
    new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";

localSettings.Values["exampleCompositeSetting"] = composite;

Retrieve a setting

Windows.Storage.ApplicationDataCompositeValue composite = 
   (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];

if (composite == null)
{
   // No data
}
else
{
   // Access data in composite["intVal"] and composite["strVal"]
}

Upvotes: 3

Related Questions