我想在Xamarin Forms应用程序中,将一小段数据本地保存在设备上,以便稍后检索。
我不想使用SQL Lite、App.Config或将其保存为文件,它只是一个字符串。
这种方式是否可行?如果可以,有没有示例?
我想在Xamarin Forms应用程序中,将一小段数据本地保存在设备上,以便稍后检索。
我不想使用SQL Lite、App.Config或将其保存为文件,它只是一个字符串。
这种方式是否可行?如果可以,有没有示例?
将值保存到本地数据库:
string userName = "abc.def";
Application.Current.Properties["username"] = userName;
await Application.Current.SavePropertiesAsync();
获取项目中任何位置的值:
if (Application.Current.Resources.ContainsKey("username"))
{
string UserName = Application.Current.Properties["username"].ToString();
}
在 [] 方括号内使用相同的键。
那么 属性字典 呢?
它是持久的,可以从任何地方访问!
Application.Current.Properties ["email"] = someClass.email;
使用
Application.Current.Properties
只有在应用程序的生命周期内,其中某些文本才可用。如果你关闭并重新打开它们,就会消失。
最终我使用了SimpleIoC,它比使用1或2行要大得多,所以我很快就会更新我的答案,并提供代码,以防有人需要它。
如果您需要在Xamarin应用程序(Xaml或Code behind)中使用的常量,请使用App.xaml中的Application.Resources进行存储。
https://developer.xamarin.com/guides/xamarin-forms/xaml/resource-dictionaries/
在你的 App.xaml 文件中:<?xml version="1.0" encoding="UTF-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:clr="clr-namespace:System;assembly=mscorlib"
x:Class="ResourceDictionaryDemo.App">
<Application.Resources>
<ResourceDictionary>
<clr:String x:Key="MyConstString">My string</clr:String>
</ResourceDictionary>
</Application.Resources>
</Application>
从XAML访问静态资源:
{StaticResource MyConstString}
来自C#:
Application.Current.Resources["resourceName"]