简体   繁体   English

Xamarin表单内部构造函数显示警告未显示?

[英]Xamarin forms inside Constructor display alert not showing?

I want to display alert in my main page loading time. 我想在主页加载时显示警报。 So i declared display alert in my constructor. 所以我在构造函数中声明了显示警报。 But i didn't get any response. 但我没有得到任何回应。

I have attached my sample code. 我附上了我的示例代码。

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();
    }

}

The constructor is meant to keep Initialization code. constructor用于保留Initialization代码。 The OnAppearing() method is called when the Page is about to be displayed.The displayAlert() will succeed inside this method. OnAppearing()时,该方法被调用Page即将被displayed.The displayAlert()将这个方法里面取得成功。 This is the sample code. 这是示例代码。

protected override void OnAppearing()
    {

        Application.Current.MainPage.DisplayAlert("Success", "Saved", "OK");

        base.OnAppearing();

}

Keep you initialization code in the constructor or new Task(Init).Start(); 保持constructor函数中的初始化代码或new Task(Init).Start(); as suggested in other answer. 正如其他答案所示。 Save the status of if else in field of type bool . else if的状态保存在bool类型的字段中。 Alter the message in the OnAppearing() method according to the field. 根据字段更改OnAppearing()方法中的消息。

You can not directly await a Task within the .ctor of a class (search SO there are plenty of Q&A on this). 你不能直接await类的.ctor中的Task (搜索SO有很多问答)。

In your .ctor, after the InitializeComponent start a void Task (fire and forget style): 在你的.ctor中,在InitializeComponent启动一个void Task(fire和forget样式):

new Task(Init).Start();

The void task Init will look like: void任务Init看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM