C# 读取另一页上的变量集
我正在构建一个windows phone应用程序,我需要一个设置页面。我知道如何设置设置,但现在我需要知道如何从主页上读取设置 因此,从MainPage.xaml.cs,我需要检查Settings.cs上的ExitAlert是真是假,我不知道该怎么做。我相信这很简单C# 读取另一页上的变量集,c#,xaml,windows-phone-7,C#,Xaml,Windows Phone 7,我正在构建一个windows phone应用程序,我需要一个设置页面。我知道如何设置设置,但现在我需要知道如何从主页上读取设置 因此,从MainPage.xaml.cs,我需要检查Settings.cs上的ExitAlert是真是假,我不知道该怎么做。我相信这很简单 谢谢。通常在windows中,临时设置(例如特定实例)存储在“PhoneApplicationService.Current.State”中 永久设置将存储在“System.IO.IsolatedStorage.IsolatedSt
谢谢。通常在windows中,临时设置(例如特定实例)存储在“PhoneApplicationService.Current.State”中 永久设置将存储在“System.IO.IsolatedStorage.IsolatedStorage settings.ApplicationSettings”中 根据你的询问 您可以在设置页面中存储该值,如下所示
if(PhoneApplicationService.Current.State.Contains("ExitAlert"))
PhoneApplicationService.Current.State["ExitAlert"] = value;
else
PhoneApplicationService.Current.State.Add("ExitAlert", value);
您可以从主页访问该值,如下所示
if(PhoneApplicationService.Current.State.Contains("ExitAlert"))
value = (bool)PhoneApplicationService.Current.State["ExitAlert"];
if(value == true)
Messagebox.Show("Exit alert is set");
希望它能解决您的问题。要在应用程序实例中跨页面共享一个值,请将该值添加到生成页面中的应用程序资源中,然后从另一个页面中的资源中获取该值 下面是一些我经常使用的助手方法,它们说明了如何使用应用程序资源
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 );
}
publicstatict GetResource(对象键),其中T:class
{
将Application.Current.Resources[key]返回为T;
}
公共静态T GetResourceValueType(对象键),其中T:struct
{
对象值=Application.Current.Resources[key];
返回值(值!=null)
?(T)值
:新T();
}
公共静态void SetResource(对象键、对象资源)
{
if(Application.Current.Resources.Contains(key))
Application.Current.Resources.Remove(键);
Application.Current.Resources.Add(key,resource);
}
请注意,SetResource的工作原理是,一旦设置了应用程序资源,就无法更改其值,因此它会删除旧资源,然后添加新资源。GetResource和GetResourceValueType之间的区别在于类型是CLR资源类型(即类)还是CLR值类型(即int或bool等结构)
对于您的示例,您可以这样使用它们:
bool exitAlert_Page1 = true;
SetResource( "ExitAlert", exitAlert );
// elsewhere...
bool exitAlert_Page2 = GetResourceValueType<bool>( "ExitAlert" );
bool exitAlert_Page1=true;
SetResource(“ExitAlert”,ExitAlert);
//其他地方。。。
bool exitAlert_Page2=GetResourceValueType(“exitAlert”);
我通常使用这些helper方法来实现C#属性的get和set方法,因此使用的“key”值仅限于属性定义
更新:因为这之前已经出现过,我在一篇博客文章中总结了这篇文章,并做了一些小的改进和可下载的代码。享受吧 使用隔离存储将在应用程序的所有实例中共享价值。我认为问题在于只要求在单个应用程序实例中跨页面共享价值。来自应用程序上一次调用的值不应可用于新调用。如果是这样的话,我建议改用应用程序资源(请参见我的答案),因为它们的作用域是应用程序实例。我已经将其设置为将其存储在独立存储中,那么访问值的示例是否仍然有效?@Rev,是的,您可以使用独立存储在应用程序内跨页面共享值。我要提出两个问题。首先,使用隔离存储的访问速度将比使用应用程序资源慢。其次,您需要注意确保应用程序先前执行时隔离存储中的值不会在新的应用程序执行中产生任何不需要的情况。这两者都不是不可克服的。因此,可以稍微小心地使其工作,这并不适合您的情况。@Rev,我同意visual Stuart先生的观点,即隔离存储需要更多的时间,这会影响您的应用程序性能,因此最好使用PhoneApplicationService.Current.State临时存储设置。