我们如何在Xamarin.Forms中将App设置以键值对的形式存储和检索? 例如,当应用程序关闭时,我们可以存储用户首选项,在重新启动应用程序时,我们能够获取这些值。
我们如何在Xamarin.Forms中将App设置以键值对的形式存储和检索? 例如,当应用程序关闭时,我们可以存储用户首选项,在重新启动应用程序时,我们能够获取这些值。
也可以使用 Properties Dictionary
来存储数据:
Application.Current.Properties ["id"] = someClass.ID;
获取数据的方法:
if (Application.Current.Properties.ContainsKey("id"))
{
var id = Application.Current.Properties ["id"] as int;
// do something with id
}
Application
对象(在VS中,您可以获取一个从中继承的App
类,我认为Xamarin Studio模板可能略有不同)具有专门用于此的Properties
字典。如果您需要确保立即保存属性,可以调用Application.SavePropertiesAsync
方法。
Xamarin.Forms
的相关内容。由于这是在设备级别上实现的,因此您可以从任何Forms项目、PCL库或您的应用程序中的本机项目访问这些设置。
private const string UserNameKey = "username_key";
private static readonly string UserNameDefault = string.Empty;
public static string UserName
{
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
Akavache
(用于缓存,但正在考虑转移到Realm以提高速度并为未来项目删除SQLite依赖)。但是对于存储一些应用程序设置,它有点过头了... - SushiHangover<Application.Resources>
<ResourceDictionary>
<Style x:Key="SmallLabel" TargetType="Label">
<Setter Property="TextColor" Value="Gray" />
<Setter Property="Font" Value="{StaticResource FontItalicSmall}" />
</Style>
</ResourceDictionary>
</Application.Resources>
然后在 C# 代码中像这样检索它们:
var style = (Style)Application.Current.Resources["SmallLabel"];
/* You need to using Xamarin.Essentials
If you do not have Xamarin.Essentials installed,
install it from (NuGet Package Manager)
*/
// Add a reference to Xamarin.Essentials in your class
using Xamarin.Essentials;
// To save a value for a given key in preferences
Preferences.Set("my_key", "my_value");
// To retrieve a value from preferences or a default if not set
var myValue = Preferences.Get("my_key", "default_value");
// To check if a given key exists in preferences
bool hasKey = Preferences.ContainsKey("my_key");
// To remove the key from preferences
Preferences.Remove("my_key");
// To remove all preferences
Preferences.Clear();
请查看此链接: https://learn.microsoft.com/zh-cn/xamarin/essentials/preferences?tabs=android