我正在构建一个windows phone应用程序,我需要一个设置页面。我知道了如何设置设置,但现在我需要知道如何从主页读取它们。
因此,我需要从MainPage.xaml.cs检查Settings.cs上的ExitAlert是否为真或假,但我不知道怎么做。我确定这是很简单的事情。
谢谢。
发布于 2011-11-11 23:13:25
要在应用程序实例内的页面之间共享值,请将该值添加到生产页面中的应用程序资源,然后从另一个页面中的资源中获取该值。
下面是一些我经常使用的助手方法,它们说明了如何使用应用程序资源。
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 );
}请注意,SetResource解决了这样一个问题:一旦设置了应用程序资源,您就无法更改它的值,因此它会删除旧资源,然后添加一个新资源。GetResource和GetResourceValueType之间的区别在于类型是CLR资源类型(即,类)还是CLR值类型(即,结构,如int或bool)。
对于您的示例,您将按如下方式使用它们:
bool exitAlert_Page1 = true;
SetResource( "ExitAlert", exitAlert );
// elsewhere...
bool exitAlert_Page2 = GetResourceValueType<bool>( "ExitAlert" );我通常使用这些帮助器方法来实现C#属性的get和set方法,以便使用的'key‘值仅限于属性定义。
更新:由于之前已经出现过这个问题,我在博客文章中总结了这一点,并做了一些小的改进和可下载的代码。享受吧!
https://stackoverflow.com/questions/8089758
复制相似问题