Xamarin.Forms: Application.Current.MainPage.DisplayAlert() 抛出 System.NullReferenceException

huangapple go评论72阅读模式
英文:

Xamarin.Forms: Application.Current.MainPage.DisplayAlert() throws System.NullReferenceException

问题

我正在从一个单独的类中使用 `Application.Current.MainPage.DisplayAlert`,但是我得到了这个错误:

> System.NullReferenceException: '对象引用未设置到对象的实例。'

**App.xaml.cs**

```c#
public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPage());
    }
}

MainPage.cs

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();

        DisplayMessage.Display();
    }
}

DisplayMessage.cs

public class DisplayMessage
{
    public async void Display()
    {
        await Application.Current.MainPage.DisplayAlert("Hello World", "Welcome", "OK");
    }
}

我找到了这个文章提出了这个解决方案,但没有帮助:

public static Page RootPage;

public App()
{
    InitializeComponent();
    
    MainPage = new MainPage();
    
    App.RootPage = this.MainPage;
}
    
App.RootPage.DisplayAlert(title, message, ok);

有人知道怎么解决吗?非常感谢。


<details>
<summary>英文:</summary>

I&#39;m using `Application.Current.MainPage.DisplayAlert` from a separate class and I&#39;m getting this error:

&gt; System.NullReferenceException: &#39;Object reference not set to an instance of an object.&#39;

**App.xaml.cs**

```c#
public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPage());
    }
}

MainPage.cs

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();

        DisplayMessage.Display();
    }
}

DisplayMessage.cs

public class DisplayMessage
{
    public async void Display()
    {
        await Application.Current.MainPage.DisplayAlert(&quot;Hello World&quot;, &quot;Welcome&quot;, &quot;OK&quot;);
    }
}

I found this article proposing this solution but it doesn't help

public static Page RootPage;

public App()
{
    InitializeComponent();
    
    MainPage = new MainPage();
    
    App.RootPage = this.MainPage;
}
    
App.RootPage.DisplayAlert(title, message, ok);

Does someone have a direction to find out ? Thanks a lot.

答案1

得分: 1

问题在于你在MainPage实例完成构建之前尝试访问它。

不要这样做:

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();

        DisplayMessage.Display();
    }
}

你可以这样做,应该可以工作:

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();
    }

    public void ShowMessage()
    {
        DisplayMessage.Display();
    }
}

然后,在构建完成之后,可以调用ShowMessage()方法,这将显示消息。

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new MainPage();

        MainPage.ShowMessage();
    }
}

现在,你的代码整体设计可能会有争议,但是进行这些更改应该会得到一个可用的解决方案。

更新:

你可能还希望在以下代码段中添加空值检查:

public class DisplayMessage
{
    public async void Display()
    {
        //注意&quot;?&quot;
        await Application.Current.MainPage?.DisplayAlert(&quot;Hello World&quot;, &quot;Welcome&quot;, &quot;OK&quot;);
    }
}

注意?,它确保仅当MainPage设置为一个实例时才调用DisplayAlert()

英文:

The problem is that you're trying to access the MainPage instance before it has finished construction.

Instead of doing this:

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();

        DisplayMessage.Display();
    }
}

You can do the following, which should work:

public partial class MainPage : ContentPage
{
    private static readonly DisplayMessage DisplayMessage = new();

    public MainPage()
    {
        InitializeComponent();
    }

    public void ShowMessage()
    {
        DisplayMessage.Display();
    }
}

Then, after construction finished, the ShowMessage() method can be called, which in turn will display the message.

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new MainPage();

        MainPage.ShowMessage();
    }
}

Now, the overall design of your code is debatable, but making these changes should lead to a usable solution.

Update:

You may also want to add a null-check to the following piece of code:

public class DisplayMessage
{
    public async void Display()
    {
        //note the &quot;?&quot;
        await Application.Current.MainPage?.DisplayAlert(&quot;Hello World&quot;, &quot;Welcome&quot;, &quot;OK&quot;);
    }
}

Note the ? which serves to ensure that DisplayAlert() only gets called when MainPage is set to an instance.

答案2

得分: 1

🤔为了仅仅显示一个警告,为什么需要这么多的代码呢?

为了确保在页面加载后显示警告,我们可以通过Loaded事件处理程序传递警告代码,就像这样:

MainPage.xaml:

&lt;ContentPage
         Loaded=&quot;AfterContentPageLoaded&quot;&gt;

MainPage.xaml.cs:

   private void AfterContentPageLoaded(object sender, EventArgs e)
{
    Application.Current.MainPage?.DisplayAlert(&quot;你好&quot;, &quot;这真的很简单&quot;, &quot;确定&quot;);
}

你也可以在MainPage.xaml.cs页面的Loaded事件处理程序中传递来自DisplayMessage.cs类的方法。

❤️

英文:

🤔 What is the Need of Such a Big Code for Just an Alert ?

To Make sure, Alert is Shown after Page is Loaded We Can Just Pass Alert Code through Loaded Event Handler , Just Do Like This:

On MainPage.xaml :

&lt;ContentPage
         Loaded=&quot;AfterContentPageLoaded&quot;&gt;

On MainPage.xaml.cs :

   private void AfterContentPageLoaded(object sender, EventArgs e)
{
    Application.Current.MainPage?.DisplayAlert(&quot;Hello&quot;, &quot;It was So Simple&quot;, &quot;OK&quot;);
}

You can also pass your method from your DisplayMessage.cs class into Loaded event Handler on MainPage.xaml.cs page.

❤️

huangapple
  • 本文由 发表于 2023年3月3日 20:05:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定