微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决“名称“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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。