c# - xamarin 表单无法保持最后状态
问题描述
当我关闭应用程序并启动它但不工作时,我试图保持我的 xamarin 表单的某些变量的状态
我有 2 个变量“isconnected”和“eric”
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
在我重新启动应用程序并尝试像这样获取我的变量的值后关闭应用程序:
((bool)App.Current.Properties["UserIsConnected"] ))
((string)App.Current.Properties["userName"] ))
我有这个错误:
System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.
如何保存我的变量并在重新启动应用程序时获取它们?
在此先感谢您的帮助
解决方案
在我们获取它的值之前,您需要检查该值是否存在。你可以这样做:
private async Task saveDataAsync() {
if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
//Do something awesome.
bool UserIsConnected = ((bool)App.Current.Properties["UserIsConnected"]);
string name = ((string)App.Current.Properties["userName"]);
System.Diagnostics.Debug.WriteLine("UserIsConnected= " + UserIsConnected +" name =" + name);
}
else {
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
}
}
推荐阅读
- c# - 如何在 C# 模型中命名我的 XML 标头 'header list-id: "inventory"'?
- python - Python子类属性不会初始化
- elasticsearch - 当我使用 JsonNetSerializer 时,程序映射所有字段而不是我选择的字段
- python - 如何使用 pyspark 仅按特定功能进行分组
- java - Maven 错误:未设置 JAVA_HOME 环境变量
- java - 使 logback 具有静态线程池大小
- google-cloud-platform - 将文件从 GCP 存储桶发送到第 3 方 pdf 转换器
- c# - 人们使用 get 属性的原因是什么?放; 而不是字段?
- python - 我们可以在 REST API 上设置条件吗
- security - 了解由未定义行为清理程序 (UBSan) 触发的运行时错误