我以前从未使用过消息中心,并且在应用程序之间传递消息时可能会犯一些荒谬的错误。我尝试从 Xamarin.Android 向 Xamarin.Forms 发送消息。
Xamarin.Android 项目代码:
MessagingCenter.Send(Xamarin.Forms.Application.Current, "MessageReceived", "new message");
Xamarin.Forms:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = (new MasterDetailPage()
{
Master = new MenuPage { Title = "Title" },
Detail = new NavigationPage(new XxmsApp.MainPage()) { BarBackgroundColor = Color.Black }
});
MessagingCenter.Subscribe<App>(
this,
"MessageReceived",
(sender) =>
{
var StartPage = (((MainPage as MasterDetailPage).Detail as NavigationPage).RootPage as XxmsApp.MainPage);
StartPage.DisplayAlert(
"message",
"message received",
"ok");
});
}
// ...
}
但是指定为第三个参数的Subscribe<App>
方法永远不会被调用。我也试过这个:
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send(Xamarin.Forms.Application.Current, "MessageReceived", "new message");
});
但什么都没有。
我究竟做错了什么?