如果您想要临时会话存储(应用的生命周期,包括用户使用后退按钮返回您的应用的时间),那么您可以使用 Phone State。电话状态类似于 ASP.NET 中的会话状态。它只是一个带有字符串键的(可序列化)对象的字典,不会在您的应用程序启动时维护,但当您的应用程序从 Back Stack 导航到时,它会恢复。
这是一个用于恢复名为 myObject 的自定义对象的示例:
private CustomObject myObject;
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
//Save to State when leaving the page
PhoneApplicationService.Current.State["myObject"] = myObject;
base.OnNavigatedFrom(args);
}
protected override void OnNavigatedTo(NavigationEventArgs args)
{
if (PhoneApplicationService.Current.State.ContainsKey("myObject"))
{
//Restore from State
myObject = (CustomObject)PhoneApplicationService.Current.State["myObject"];
}
else
{
//No previous object, so perform initialization
myObject = new myObject();
}
}
如果您需要在应用程序的所有实例中存储设置,请查看 IsolatedStorageSettings,它非常适合此操作。根据您的需要,还有其他选项 (Charles Petzold has a free eBook with some great examples)。
不知道为什么上面的代码对你不起作用,但另一种选择是使用一个应用程序属性,该属性是使用 IsolatedStorageSettings 保存的。这是一个例子:
在您的 App.xaml.cs 中:
public bool VibrationOn { get; set; }
private void Application_Launching(object sender, LaunchingEventArgs e)
{
LoadSettings();
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
LoadSettings();
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
SaveSettings();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
SaveSettings();
}
private void LoadSettings()
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
bool vo;
if (settings.TryGetValue<bool>("VibrationOn", out vo))
VibrationOn = vo;
else
VibrationOn = true;
}
private void SaveSettings()
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["VibrationOn"] = VibrationOn;
}
然后,您可以使用以下代码在应用程序的任何位置访问此属性:
if (Application.Current.VibrationOn)
{
VibrateController.Default.Start(TimeSpan.FromMilliseconds(200));
}