How to use MessagingCenter to pass a message from an Android project to the PCL project?

I'm struggling to pass a message from my Android project to my PCL project using MessagingCenter.
In my PCL project, I have a ContentPage called "AboutPage", while on the Android project I have a ScaleImageView class that inherits from ImageView.

When an event occurs on ScaleImageView, I want to pass a message to the AboutPage. Here's what I have so far...

On ScaleImageView.cs

var mp = App.Current.MainPage; MessagingCenter.Send<AboutPage, string>((AboutPage)mp, "PageSwipe", "NextPage");

On AboutPage

MessagingCenter.Subscribe<AboutPage, string>(this, "PageSwipe", (sender, arg) => { DisplayAlert("Message Received", "arg=" + arg, "OK"); });

But this is not working, I get an error when the MessagingCenter code executes, which I wrote based on this post...
https://forums.xamarin.com/discussion/26681/need-to-get-message-back-to-forms-pcl-from-android-prj

Tagged:

Answers

  • adamkempadamkemp USInsider, Developer Group Leader mod

    What error are you getting?

  • rarenivarrarenivar USMember ✭✭

    @adamkemp - I get an unhandled exception...

    09-29 14:45:17.334 I/MonoDroid(29292): UNHANDLED EXCEPTION:
    09-29 14:45:17.344 I/MonoDroid(29292): System.InvalidCastException: Cannot cast from source type to destination type.
    

    For some reason, I don't think it likes it when I cast "mp" as an AboutPage.
    In the post that I mentioned, they get the MainPage a little different...
    var mp = App.GetMainPage ();

    This does not work on my project, there isn't a GetMainPage function in the App object.

  • rarenivarrarenivar USMember ✭✭

    I got the MessagingCenter working. You don't have to pass the Sender class. For the send code I have...

    direction = "Backwards"; MessagingCenter.Send(direction, "PageSwipe");

    And the subscriber...
    MessagingCenter.Subscribe<string>(this, "PageSwipe", (sender) => { DisplayAlert("Swipe", "Direction detected: " + sender, "OK"); });

Sign In or Register to comment.