我无法使用Xamarin Forms中的消息中心发送字符串。

huangapple go评论58阅读模式
英文:

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&lt;Page, string&gt;(this, &quot;searchText&quot;, &quot;John&quot;);

MessagingCenter.Subscribe&lt;Page, string&gt;(this, &quot;searchText&quot;, async (sender, arg) =&gt;
{
    await DisplayAlert(&quot;Message received&quot;, &quot;arg=&quot; + arg, &quot;OK&quot;);
});


huangapple
  • 本文由 发表于 2023年7月10日 22:10:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定