XamarinのPCL使っているとApplication.Currentがnullになりました。
まず、何がしたかったというとApplication.Current.Propertyを使って数値の保存を行いたかったんです。
しかし、いくらデバッグをしてもCurrentがNullになり、保存、読み込み全てできないのです。
仮に
App.cs
using Xamarin.Forms;
namespace Hoge
{
public partial class App : Application
{
private Hoge hoge = new Hoge();
public App()
{
InitializeComponent();
MainPage = new NavigationPage(hoge)
{
BarBackgroundColor = Color.FromRgba(0.2, 0.6, 0.86, 1),
BarTextColor = Color.White
};
}
}
}
Hoge.cs
using System;
using Xamarin.Forms;
namespace Hoge
{
public partial class Hoge : ContentPage
{
public Hoge()
{
InitializeComponent();
var hoge = Application.Current.Properties["hoge"];
}
}
}
があったとすると、Application.Current.Properties["hoge"]でCurrentがnullと言われます。
パッと見は良さげなんですけどね…
解決方は簡単で、App.csを
App.cs
using Xamarin.Forms;
namespace Hoge
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new Hoge())
{
BarBackgroundColor = Color.FromRgba(0.2, 0.6, 0.86, 1),
BarTextColor = Color.White
};
}
}
}
にするだけです。Xamarinのタイミングの問題らしく、Appがインスタンス化されてないと、Currentがnullらしいです。