在 App.cs (Xamarin) 中显示 DisplayAlert [英] Show an DisplayAlert at App.cs (Xamarin)

查看:47
本文介绍了在 App.cs (Xamarin) 中显示 DisplayAlert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试不断跟踪用户是否连接到互联网.

I am currently trying to constantly keep track whether the user is connected to internet or not.

我有检查连接的代码,我希望能够在用户使用应用程序时未连接到互联网时显示弹出窗口.

I have the codes to check for connectivity and I want to be able to show a popup whenever the user is not connected to internet while using the app.

但是,我不能将 DisplayAlert 放在 App.cs(错误:DisplayAlert 在上下文中不存在).

However, I can't put DisplayAlert at App.cs (Error: DisplayAlert does not exist in context).

我可以知道为什么会这样吗?

May I know why is this so?

App.cs

public App()
{
    InitializeComponent();

    var seconds = TimeSpan.FromSeconds(1);
    Xamarin.Forms.Device.StartTimer(seconds,
        () =>
        {
            CheckConnection();
        });
}

private async void CheckConnection()
{
    if (!CrossConnectivity.Current.IsConnected)
        await DisplayAlert("No Internet Connection", "Please connect to Internet", "OK");
    else
        return;
}

推荐答案

DisplayAlert 是页面类的一个方法.但是,您的应用程序具有MainPage"属性.所以只要设置了主页(启动时设置后应该总是这样)就可以使用

DisplayAlert is a method of the page class. However your app has a 'MainPage' property. So as long as the main page is set (should always be so after it's set during startup) you can use

Application.Current.MainPage.DisplayAlert

或来自 App.cs

MainPage.DisplayAlert

这篇关于在 App.cs (Xamarin) 中显示 DisplayAlert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆