Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show an DisplayAlert at App.cs (Xamarin)

Tags:

c#

xamarin

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.

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;
}
like image 212
CodeName Avatar asked Apr 06 '18 08:04

CodeName


2 Answers

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

or from within App.cs

MainPage.DisplayAlert
like image 172
App Pack Avatar answered Oct 18 '22 10:10

App Pack


So you can do this, is working for me

Device.BeginInvokeOnMainThread(async () => { await Application.Current.MainPage.DisplayAlert("No Internet Connection", "Please connect to Internet", "OK"); });

like image 38
Dominik Avatar answered Oct 18 '22 09:10

Dominik