Reputation: 18550
I'm building a windows phone app, and I need a settings page. I figured out how to set the settings but now I need to know how to read them from the main page.
So from MainPage.xaml.cs I need to check if ExitAlert is true or false on Settings.cs, and I can't figure out how. I'm sure it's something simple.
Thanks.
Upvotes: 2
Views: 941
Reputation: 661
For sharing a value across pages within an application instance, add the value to the application resources in the producing page, and get the value from the resource in another.
Here are some helper methods that I use frequently, which illustrate how to use the application resources.
public static T GetResource<T>( object key ) where T : class
{
return Application.Current.Resources[ key ] as T;
}
public static T GetResourceValueType<T>( object key ) where T : struct
{
object value = Application.Current.Resources[ key ];
return (value != null)
? (T)value
: new T();
}
public static void SetResource( object key, object resource )
{
if ( Application.Current.Resources.Contains( key ) )
Application.Current.Resources.Remove( key );
Application.Current.Resources.Add( key, resource );
}
Note that SetResource works around the fact that you cannot change the value of an application resource once it is set, so it removes the old resource and then adds a new one. The difference between GetResource and GetResourceValueType is whether the the type is a CLR resource type (i.e., a class) or a CLR value type (i.e., a struct such as int or bool).
For your example, you would use them like this:
bool exitAlert_Page1 = true;
SetResource( "ExitAlert", exitAlert );
// elsewhere...
bool exitAlert_Page2 = GetResourceValueType<bool>( "ExitAlert" );
I usually use these helper methods to implement a C# property's get and set methodsso that the 'key' value used is limited to the property definition.
Update: Since this has come up before, I wrapped this up, with a few small improvements and downloadable code, in a blog post http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/ . Enjoy!
Upvotes: 0
Reputation: 1525
Normally in windows temporary settings (For particular instance) are stored in the "PhoneApplicationService.Current.State" and the Permanent settings will be stored in the "System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings"
As per your query
you can store the value in the settings page as follows
if(PhoneApplicationService.Current.State.Contains("ExitAlert"))
PhoneApplicationService.Current.State["ExitAlert"] = value;
else
PhoneApplicationService.Current.State.Add("ExitAlert", value);
and you can access the value from the main page as follows
if(PhoneApplicationService.Current.State.Contains("ExitAlert"))
value = (bool)PhoneApplicationService.Current.State["ExitAlert"];
if(value == true)
Messagebox.Show("Exit alert is set");
Hope it solve your issue.
Upvotes: 2