LoginSignup
6
3

More than 5 years have passed since last update.

XamarinでApplication.Currentがnullになった!?

Posted at

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らしいです。

6
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3