【问题标题】:MessagingCenter message not being received when data is passed from Android to PCL数据从 Android 传递到 PCL 时未收到 MessagingCenter 消息
【发布时间】:2017-08-17 16:49:18
【问题描述】:

我正在尝试将数据从 MainActivity 发送回 PCL 视图。当我发送没有数据的消息时,它会收到它。但是当我尝试用它传回一个字符串时,代码永远不会到达。

在 MainActivity 中:

if(data != null)
            {

                MessagingCenter.Send<object, string>(this, data, "MapIntentReceived");
                MessagingCenter.Send<object>(this, "MapIntentReceived");

            }

在 PCL 中:

            MessagingCenter.Subscribe<object, string>(this, "MapIntentReceived",
                async (sender, roomString) =>
                {   //his code is not reached
                    await SearchForRooms(roomString);
                });

            MessagingCenter.Subscribe<object>(this, "MapIntentReceived",
                async (sender) =>
                {   //this code is reached
                    await SearchForRooms("blah");
                });

感谢您的帮助。

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    要发送带参数的消息,请在 Send 方法调用中包含 Type 泛型参数和参数的值。

    MessagingCenter.Send<MainPage, string> (this, "MapIntentReceived", data);
    

    要随消息传递参数,请在订阅通用参数和操作签名中指定参数类型。

    MessagingCenter.Subscribe<MainPage, string> (this, "MapIntentReceived", (sender, arg) => {
        await SearchForRooms(arg);
    });
    

    退订

    MessagingCenter.Unsubscribe<MainPage, string> (this, "MapIntentReceived");
    

    【讨论】:

    • 消息来自 MainActivity,而不是 MainPage,这就是为什么我要传回一个通用对象。但是您指出我在错误的参数位置传回了数据字符串,这解决了我的问题。谢谢!
    • @WillNasby,您可以使用任何对象代替 MainPage。
    • 如何使用任何对象?发件人和订户类型不应该匹配吗?如果您在发送上使用 MainActivity,在订阅上使用 MainPage?这行得通吗?
    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 2020-10-19
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多