Xamarin.Forms中的Application.Current Null异常

时间:2015-02-26 02:11:21

标签: c# xamarin.forms

在Xamarin.Forms应用程序中,我使用Application.Current.Properties来保存设置。当我的LoginPage加载时,我想看看是否存在设置,但我得到一个异常,说Application.Current是Null。这是(已清理的)代码,它位于LoginPage:

 private bool AuthTokenExists()
        {
            // The following line throws the exception
            if (Application.Current.Properties.ContainsKey("First") && Application.Current.Properties.ContainsKey("Second"))
            {
                if (Application.Current.Properties["First"] as string != null &&
                    Application.Current.Properties["Second"] as string != null)
                return true;
            }
            else
            {
            return false;
            }
        }

我已经读过你不能在App构造函数中调用Application.Current.Properties,但这是在ContentPage中。我有什么想法得到例外?提前谢谢!

2 个答案:

答案 0 :(得分:2)

在您从平台项目中调用LoadApplication()之前,它是null。

MainActivity.cs中的LoadApplication( new App() );和PCL或Shaired中的App类必须是Applciation而不是内容页面。

然后您可以在应用程序的任何位置使用您的现有代码(包括您提到的内容页面),它不会给出Null异常。

答案 1 :(得分:1)

目前,Xamarin-VS扩展中还有一个( - )错误,因此调试器中的应用程序对象不可见。 因此,我填写了bugzilla中的一个错误。 但是在RunTime(没有调试器)它应该运行(至少使用较新的XF版本)。 此外,某些设备存在一些问题(例如我的Android平板电脑SM-T900),因此属性未正确存储(听起来不错:-) 在最后一个XF版本中,现在可以显式存储属性(新方法)

所以,我建议你:
- 更新到允许显式存储的版本(如果尚未使用)
- 通过app-start确定默认值 - 使用新方法保存 - 部署到设备
- 重新测试,如果它工作(例如显示具有属性值的DisplayAlert)

如果没有,您应填写BugZilla中的错误。

希望这会有所帮助......