“名称“DisplayAlert”在当前上下文中不存在” Xamarin C#

问题描述

我正在尝试使用以下代码在 Xamarin 中发出警报:

    private async void AboutMe_Click(object sender,EventArgs e)
    {
        await displayAlert("Alert","You have been alerted","OK");
    }

但是 VS 显示了这个错误

    The name "displayAlert" does not exist in current context.

我在互联网上搜索解决方案,发现了这个:

    await App.Current.MainPage.displayAlert ("Hello","No");

还有:

    await Application.Current.MainPage.displayAlert ("Hello","No");

我尝试了这些新代码,但它们显示了另一个错误

    Application does not contain a deFinition for "Current"    ....

解决方法

在 Xamarin.forms 中,如果您在页面点击事件的代码中使用了此代码,则可以尝试以下代码。

 public partial class Page4 : ContentPage
{
    public Page4()
    {
        InitializeComponent();
    }

    async void Button_Clicked(object sender,EventArgs e)
    {
        await DisplayAlert("Alert","You have been alerted","OK");
    }
}

当您在 Page 中不使用它时,使用下面的代码与之前的代码相同。使用 App 而不是 Application

 await App.Current.MainPage.DisplayAlert("Alert","OK");

输出:

enter image description here