我有一个使用 rg 插件弹出扩展的弹出窗口,它应该使用消息中心发送一个布尔值,但调用此弹出窗口的方法从不等待结果。
下面你们可以看到 DisplayAlert.cs 文件,它有一个显示模式窗口并使用消息中心接收布尔值的方法:
using Rg.Plugins.Popup.Extensions;
using Xamarin.Forms;
using System.Threading.Tasks;
namespace MasterDetailPageNavigation.XAML
{
public class Alerta
{
public Alerta(){}
public class Retorno
{
public bool valor { get; set; }
}
public bool retorno;
public async Task<bool> ShowAlert(string tipo, string titulo, string msg, string btnconfirm, string btncancel)
{
await App.Current.MainPage.Navigation.PushPopupAsync(
new DisplayAlert(tipo, titulo, msg, btnconfirm, btncancel)
);
MessagingCenter.Subscribe<Retorno>(this, "DisplayAlert", (value) =>
{
retorno = value.valor;
});
return retorno;
}
}
}
这是弹出 ContentPage 背后的代码,正如我所说,它必须由消息中心返回 true 或 false:
using Xamarin.Forms;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Extensions;
namespace MasterDetailPageNavigation.XAML
{
public partial class DisplayAlert : PopupPage
{
public DisplayAlert(string tipo, string titulo, string msg,string btnconfirm=null,string btncancel=null)
{
InitializeComponent();
switch (tipo)
{
case "ok":
XIcon.Text = "\uf058";
XIcon.TextColor = Color.FromHex("#009570");
break;
case "error":
XIcon.Text = "\uf06a";
XIcon.TextColor = Color.FromHex("#FF0000");
break;
case "confirm":
XIcon.Text = "\uf059";
XIcon.TextColor = Color.FromHex("#2181DF");
XBotoes.IsVisible = true;
XOk.IsVisible = false;
XConfirmar.Text = btnconfirm != null ? btnconfirm : XConfirmar.Text;
XCancelar.Text = btncancel != null ? btncancel : XCancelar.Text;
break;
}
XTitulo.Text = titulo;
XMsg.Text = msg;
}
void XOk_Clicked(System.Object sender, System.EventArgs e)
{
Navigation.PopPopupAsync();
}
public class Retorno
{
public bool valor { get; set; }
}
void XConfirmar_Clicked(System.Object sender, System.EventArgs e)
{
MessagingCenter.Send(new Retorno() { valor = true }, "DisplayAlert");
}
void XCancelar_Clicked(System.Object sender, System.EventArgs e)
{
MessagingCenter.Send(new Retorno() { valor = false }, "DisplayAlert");
}
}
}
最后,在主窗口中,我调用并等待该方法:
Alerta alerta = new Alerta();
// IT SHOULD AWAIT HERE BUT DON'T
bool opt = await alerta.ShowAlert("confirm", "Do you confirm?", "Message asking for confirmation","Exit","Continue here");
if (opt) //it's always false
{
Application.Current.Properties.Clear();
await Application.Current.SavePropertiesAsync();
Application.Current.MainPage = new Login();
}
我在哪里做错或错过了?