首页 > 解决方案 > 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.

如何保存我的变量并在重新启动应用程序时获取它们?

在此先感谢您的帮助

标签: c#xamarin.forms

解决方案


在我们获取它的值之前,您需要检查该值是否存在。你可以这样做:

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

推荐阅读