我想在主页加载时间中显示警报。因此,我在构造函数中声明了显示警报。但是我没有得到任何回应。
我已附加了示例代码。
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();
}
在其他答案中建议,请在constructor
或new 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");
这样的用法然后它可以正常工作。