In this article, we are going to learn:
- What is Transient Data?
- What is Application Properties?
- How to handle Transient Data by using Application Properties?
Tools
We are going to use Visual Studio 2017 and Windows 10 Operating System.
Targeted Audience
People with knowledge of XAML and C#.
What is Transient Data?
Transient data is any data in our application which is not persistent yet. For example, if you are dealing with a messaging application and the user is typing a message and your application crashes, when the user returns to application, if he didn’t find his data, he will be disappointed. So you need to handle transient data for the user's convinience or for other purposes depending upon your application logic.
In this example, we are going to handle transient data with application properties.
What are Application Properties?
The application class in our Xamarin.Forms project has a property named “Properties” which is a dictionary, so we put any object here and when the application goes into sleep mode, those objects will be persistent permanently. When the application wakes up again, the data is available. So, we don’t have to do any data access code. All we have to do is to put object in this dictionary.
How to handle Transient Data by using application properties?
Let’s go through an example and handle a data of an Entry.
Just make an entry on your content page.
Xaml
- <StackLayout>
- <Entry></Entry>
- </StackLayout>
Output on Android
Here, you will see a single entry. Now, let's make an application property to handle it.
In your Solution Explorer, go to App.xaml.cs page.
In this page, paste the following code.
Code
- private const string TitleKey = "TitleKey";
-
- public string Title
- {
- get
- {
- if (Properties.ContainsKey(TitleKey)) {
- return Properties[TitleKey].ToString();
- }
-
- return "";
- }
-
- set
- {
- Properties[TitleKey] = value;
- }
- }
Explanation
In Getter, we are going to check if the Application Properties of this name already exists or not. If it exists, then its value is returned otherwise we get a null value.
In Setter function, we can just set Application Properties.
Now, set binding context of your page to access these properties in application xaml view.
Code
- BindingContext = Application.Current;
Xaml
- <StackLayout>
- <Entry Text="{Binding Title}"></Entry>
- </StackLayout>
And set binding of entry text to Title.
Output
Any data you write in this entry is now persistent, no matter if you let your application sleep or close it. The data remains here until you change it or remove it.
Now, it’s your turn to implement it.
Thanks for reading.