Computer Magic Logo
Application Properties

Monday, April 11, 2016

Published by Aristotelis Pitaridis

Sometimes we want to store some information which will not be lost after the end of the application. This means that the next time the user will execute the application, these information will be available to read and use. This can be done using the Properties property of the Application class.

The Properties property is a dictionary with string keys and object items. The contents of the dictionary are automatically saved before the termination of the application.

The following line can be used inside an Application class in order to save the value "Hello World" using the key "MyValue".

Properties["MyValue"] = "Hello World";

The next time that our application will start we will be able to read this value using the Properties dictionary but it is a good idea to check if a value exists before we try to read the value. The following example demonstrates how to read the value within the Application class.

if (Properties.ContainsKey("MyValue"))
{
    string MyValue = (string)Properties["MyValue"];
}

In case that we want to save or read a value from another type of class we will have to do it like this.

App app = Application.Current as App;

// Save the value
app.Properties["MyValue"] = "Hello World";

// Read the value
if (app.Properties.ContainsKey("MyValue"))
{
    string MyValue = (string)app.Properties["MyValue"];
}