Xamarin形式在构造函数显示警报中未显示



我想在主页加载时间中显示警报。因此,我在构造函数中声明了显示警报。但是我没有得到任何回应。

我已附加了示例代码。

public Home()
{
    InitializeComponent();
    if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
    {
        if (System.IO.File.Exists(path + "App" + "/Data.txt"))
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await DisplayAlert("Success", "Saved", "OK");
            });
        }
        else
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await DisplayAlert("Oops", "Login Required", "OK");
            });
        }
    }
    else
    {
        GetDetails();
    }
}

constructor旨在保留Initialization代码。OnAppearing()方法将在即将显示Page时调用。displayAlert()在此方法内将成功。这是示例代码。

protected override void OnAppearing()
    {
        Application.Current.MainPage.DisplayAlert("Success", "Saved", "OK");
        base.OnAppearing();
}

在其他答案中建议,请在constructornew Task(Init).Start();中保持初始化代码。将if else的状态保存在类型bool字段中。根据字段更改OnAppearing()方法中的消息。

您无法在类的.ctor中直接await A Task(搜索,因此有很多Q& a(。

在您的.ctor中, InitializeComponent启动一个无效任务(火和忘记样式(:

new Task(Init).Start();

void Task Init看起来像:

async void Init()
{
    if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
    {
        ~~~
    }
    else
    {
        GetDetails();
    }
}

InitializeComponent()await DisplayAlert("Success", "Saved", "OK");而不是像 Application.Current.MainPage.DisplayAlert("Success", "Saved", "OK");这样的用法然后它可以正常工作。

最新更新