user11409100
user11409100

Reputation:

MessageCenter in Xamarin doesn't seem to receive a specific message

I'm playing about with the master / detail template in Xamarin Forms. When you create it, one of the things in there is to add a new item; this takes the form of a button click event:

async void Save_Clicked(object sender, EventArgs e)
{
    MessagingCenter.Send(this, "AddItem", Item);
    await Navigation.PopModalAsync();
}

And a subscription to this:

MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
    var newItem = item as Item;
    Items.Add(newItem);
    await DataStore.AddItemAsync(newItem);
});

This works fine (obviously), so I tried to emulate it; I added a new subscription:

MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
    var newItem = item as Item;
    Items.Add(newItem);
    await DataStore.AddItemAsync(newItem);
});

MessagingCenter.Subscribe<ItemDetailPage, Item>(this, "Clicked", async (obj, item) =>
{   
    var i = item as Item;
    Items.Remove(i);
    await DataStore.DeleteItemAsync(i.Id);                
});

And then broadcast it from a new button on the ItemDetailPage:

private async void MyButton_Clicked(object sender, EventArgs e)
{
    MessagingCenter.Send<Item>(viewModel.Item, "Clicked");
    await Navigation.PopAsync();
}

However, my message is never received. That is, if I put a breakpoint on the button click, it is broadcast, but a breakpoint in the subscription shows that it never arrives; the same process with the existing message shows it sends and receives.

Could I have missed something here?

Upvotes: 0

Views: 1174

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

MessagingCenter.Send <TSender,TArgs> (TSender, String, TArgs)

the Send method specifies two generic arguments. The first is the type that's sending the message, and the second is the type of the payload data being sent. To receive the message, a subscriber must also specify the same generic arguments. This enables multiple messages that share a message identity but send different payload data types to be received by different subscribers.

So , in your case you set the

MessagingCenter.Send<Item>(viewModel.Item, "Clicked");

Item here become the Sender , not the args.

If you want to add a new subscription , you can use

MessagingCenter.Send<Object,Item>(viewModel.Item, "Clicked");

And

MessagingCenter.Subscribe<Object, Item>(this, "Clicked", async (obj, item) =>
{   
    var i = item as Item;
    Items.Remove(i);
    await DataStore.DeleteItemAsync(i.Id);                
});

Upvotes: 1

Related Questions