Data Persistence In Navigation In Silverlight 3
There are situations where you need to input some data as well as navigate to a specific page and come back to enter data again. In that case usually Silverlight doesn’t persist data.
In this article we will how can we do that.
Creating Silverlight Project
Fire up Visual Studio 2008 and create a new Silverlight 3 Project. Name it as DataPersistence.
I have added some controls for the Home Page in Expression Blend.
As you see above, we have normal input scenario with TextBox, Radio Buttons and ComboBox.
Now we would create a class which will contain our persist properties.
We need to store data globally, so we would create a global property in App.xaml.cs.
In the Button Click of About we would navigate to About Page. So during that event we need to store data.
The following code is for persisting data:
toPersist.Name = txtName.Text;
toPersist.EmailId = txtEmailId.Text;
toPersist.UserType = “Admin User”;
toPersist.UserType = “Normal User”;
toPersist.Country = cmbCountry.SelectionBoxItem.ToString();
((App)Application.Current).PersistedData = toPersist;
Now we would come back to our home page and restore the persisted data.
When you come back to any navigation page, the OnNavigatedTo event is fired. So we would check there.
Add the following code in OnNavigatedTo:
txtName.Text = persisted.Name;
txtEmailId.Text = persisted.EmailId;
radioAdmin.IsChecked = true;
radioUser.IsChecked = true;
cmbCountry.SelectedItem = item;
((App)Application.Current).PersistedData = null;
That’s it. Now we would test our application.
Now click on About and you will be navigated to About page.
Now come back to the page by clicking on the Home Link on top right.
And data is persisted. That is so simple, isn’t it. Hope this article helps. J