Xamarin.forms中的共享首选项 [英] Shared Preferences in Xamarin.forms
本文介绍了Xamarin.forms中的共享首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果用户使用
Application.Current.Properties["isLoggedIn"] = "true";
,但不起作用.如果我从后台删除我的应用程序,它将再次显示登录页面,但是如果用户已登录,则应显示下一页.
but its not working. If i remove my app from background it again shows the login page but if user is logged in it should show the next page.
推荐答案
在使用应用程序属性字典"时,您需要牢记以下几点:
When using 'Application Properties Dictionary' you have to keep in mind few things:
- 根据官方文档:属性字典会自动保存到设备中".但是,如果要确保持久性,则必须显式调用
SavePropertiesAsync()
. - 属性"字典只能序列化基本类型以进行存储.尝试存储其他类型(例如List)可能会失败,并且会自动失败.
阅读官方文档仔细并注意细节.
这是一个代码示例:
Read the official documentation carefully and pay attention to details.
Here is a code example:
private async Task SaveApplicationProperty<T>(string key, T value)
{
Xamarin.Forms.Application.Current.Properties[key] = value;
await Xamarin.Forms.Application.Current.SavePropertiesAsync();
}
private T LoadApplicationProperty<T>(string key)
{
return (T) Xamarin.Forms.Application.Current.Properties[key];
}
// To save your property
await SaveApplicationProperty("isLoggedIn", true);
// To load your property
bool isLoggedIn = LoadApplicationProperty<bool>("isLoggedIn");
根据您的需求,您可以考虑本地数据库或设置插件代替.但是,只保存一些原始值,Application Properties
方法就足够了.
Base on your needs you may consider Local Database or Settings Plugin instead. However for saving just a few primitive values Application Properties
approach should be good enough.
这篇关于Xamarin.forms中的共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文