繁体   English   中英

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

[英]Save string locally on device in Xamarin Forms

我想在设备上本地保存来自 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 或代码隐藏)中使用的常量,您可以使用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"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM