在Xamarin Forms中将字符串本地保存在设备上

3

我想在Xamarin Forms应用程序中,将一小段数据本地保存在设备上,以便稍后检索。

我不想使用SQL Lite、App.Config或将其保存为文件,它只是一个字符串。

这种方式是否可行?如果可以,有没有示例?


5
你看过 Xam.Plugins.Settings 吗? - Gerald Versluis
不,但我现在会了,谢谢。 - DarkW1nter
什么样的字符串?(颜色,配置,主题,...) - OrcusZ
1
只是一段文本,一个电子邮件地址。 - DarkW1nter
PCLStorage..... - Gusman
4个回答

4

将值保存到本地数据库:

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();
}

在 [] 方括号内使用相同的键。


2

那么 属性字典 呢?
它是持久的,可以从任何地方访问!

Application.Current.Properties ["email"] = someClass.email;

编写答案: - Sreejith Sree

0

使用

Application.Current.Properties

只有在应用程序的生命周期内,其中某些文本才可用。如果你关闭并重新打开它们,就会消失。

最终我使用了SimpleIoC,它比使用1或2行要大得多,所以我很快就会更新我的答案,并提供代码,以防有人需要它。


-1

如果您需要在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"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接