[英]MessagingCenter is working on WPF but not working on Android
我創建這個應用程序是為了回答一些關於 MessagingCenter 的問題,但由於在 Android 平台上運行應用程序時出現問題,我無法繼續編寫代碼,如果您知道可能出了什么問題,請幫助我。 感謝您的支持。
我嘗試將結果頁面更改為消息中心訂閱中的新結果視圖的方式,但我不知道發生了什么,對我來說就像在訂閱中找不到消息一樣。
應用鏈接( GitHub )
在結果視圖中:
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
this.DisplayAlert("Alerta de Registro", "Mensagem DisplayAlert com registro Enviada", "Ok");
});
}
在主頁中:
ResultView ResultPage = new ResultView();
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
this.Navigation.PushAsync(ResultPage);
}
發送消息時,我在另一個屏幕上等待 DisplayAlert,但應用程序只是跳過了訂閱內的代碼。
嘗試這個
public void Registro()
{
MessagingCenter.Subscribe<ResultView,string>(this, "DisplayAlert", async (sender,message) =>
{
await DisplayAlert("Alerta de Registro", message, "Ok");
});
}
var mensagem = "teste";
MessagingCenter.Send<ResultView,string>(ResultPage, "DisplayAlert",mensagem);
這是我在項目中使用的一些示例
在我的 PCL MainPage.cs
public MainPage()
{
InitializeComponent();
MessagingCenter.Send<string>("ok", "showBar");
}
在我的 Native android 項目 MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
MessagingCenter.Subscribe<string>(this, "showBar", (sender) =>
{
this.Window.ClearFlags(WindowManagerFlags.Fullscreen);
});
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
this.Window.AddFlags(WindowManagerFlags.Fullscreen);
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
您無需創建頁面的新實例即可作為參數發送。
首先在您的GoPaginaResultComRegistro()
方法中,您應該在PushAsync
之后發送消息
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
this.Navigation.PushAsync(ResultPage);
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
}
第二個在您的ResultView
頁面中,在MainThread
中調用DisplayAlert
:
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
Device.BeginInvokeOnMainThread( async() =>
{
await DisplayAlert("Alerta de Registro", "Mensage DisplayAlert com registro Enviada", "Ok");
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.