【发布时间】:2016-09-13 00:04:33
【问题描述】:
我们如何在 Xamarin.Forms 中将应用设置存储和检索为键值对? 就像当应用程序关闭时,我们可以存储用户偏好,并且在重新启动应用程序时,我们可以获得这些值。
【问题讨论】:
标签: xamarin xamarin.forms
我们如何在 Xamarin.Forms 中将应用设置存储和检索为键值对? 就像当应用程序关闭时,我们可以存储用户偏好,并且在重新启动应用程序时,我们可以获得这些值。
【问题讨论】:
标签: xamarin xamarin.forms
使用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 方法。
【讨论】:
我将Settings Plugin for Xamarin And Windows 用于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 依赖)。但是对于存储一些应用程序设置,它有点过头了......
您可以使用 Xamarin.Essential 中包含的首选项。
/* 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://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android
【讨论】:
如果设置更多的是在运行时未更改的配置(例如,应用程序的 web.config 排序),您可以使用 App.xaml 并将值存储在字典中,如下所示:
<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"];
【讨论】: