英文:
I can't send string with messaging center in xamarin forms
问题
我可以在使用类似以下方式的类时发送对象。
MessagingCenter.Send<CariRoot>(selectedCari, "mselectedCari");
MessagingCenter.Subscribe<CariRoot>(this, "mselectedCari" ,async (sender) =>
{
SearchCari = $"{sender.CARIUNVAN}";
_SelectedCariRoot = sender;
Console.WriteLine(SearchCari);
});
但当我想发送一个字符串而不是一个对象时,我使用MessagingCenter如下,但这段代码不起作用。我不知道如何发送一个字符串。
MessagingCenter.Send<string>(searchText, "searchText");
MessagingCenter.Subscribe<string>(this, "searchText", async (sender) =>
{
SearchStateText = $"{sender}";
});
您有解决方案吗?
英文:
I can send object when I use a class like this.
MessagingCenter.Send<CariRoot>(selectedCari, "mselectedCari");
MessagingCenter.Subscribe<CariRoot>(this, "mselectedCari" ,async (sender) =>
{
SearchCari = $"{sender.CARIUNVAN}";
_SelectedCariRoot = sender;
Console.WriteLine(SearchCari);
});
But when I want to send a string not an object I use MessagingCenter like this and this code doesn't work. I can't figure how to send a string.
MessagingCenter.Send<string>(searchText, "searchText");
MessagingCenter.Subscribe<string>(this, "searchText", async (sender) =>
{
SearchStateText = $"{sender}";
});
Do you have any solution ?
答案1
得分: 1
Send 方法指定了两个泛型参数。第一个是发送消息的类型,第二个是发送的有效负载数据的类型。要接收消息,订阅者也必须指定相同的泛型参数。这使得多个共享消息标识但发送不同有效负载数据类型的消息可以被不同的订阅者接收。
此外,这个示例指定了第三个方法参数,表示要发送给订阅者的有效负载数据。在这种情况下,有效负载数据是一个 string
。
您可以参考下面的示例代码:
MessagingCenter.Send<Page, string>(this, "searchText", "John");
MessagingCenter.Subscribe<Page, string>(this, "searchText", async (sender, arg) =>
{
await DisplayAlert("Message received", "arg=" + arg, "OK");
});
英文:
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.
In addition, this example specifies a third method argument that represents the payload data to be sent to the subscriber. In this case the payload data is a string
.
You can refer to the sample code below:
MessagingCenter.Send<Page, string>(this, "searchText", "John");
MessagingCenter.Subscribe<Page, string>(this, "searchText", async (sender, arg) =>
{
await DisplayAlert("Message received", "arg=" + arg, "OK");
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论