【问题标题】:Pass Data from One Page to the other Page using Messaging Center使用消息中心将数据从一页传递到另一页
【发布时间】:2021-10-20 10:22:31
【问题描述】:

我正在尝试使用 Messaging Center 将数据从一个页面传递到另一个页面,但在我看来它不起作用。

我尝试过的:

public partial class MainPage : ContentPage
{
        public MainPage()
        {
            InitializeComponent();
        }

        async private void isClicked(object sender, EventArgs e)
        {
            MessagingCenter.Send<Page, string>(this, "Hi", "Data Sent");

            await Navigation.PushAsync(new FirstPage());
        }
    }

这是在发送后从名为 (MainPage) 的第一页发送的消息,我导航到另一个名为 FirstPage 的页面,我想在其中检索/订阅消息

在第一页我有这个代码:

   public partial class FirstPage : ContentPage
    {
        public FirstPage()
        {
            InitializeComponent();

            ReceiveMessage();
        }

        public void ReceiveMessage()
        {
            MessagingCenter.Subscribe<Page, string>(this, "Hi", (sender, values) =>
            {
                lblLabel.Text = values;
            });
        }
    }

这似乎不起作用..可能是什么问题。

【问题讨论】:

  • 您正在发送消息第二页创建之前,所以当Subscribe 执行消息时已经消失了。在这种特殊情况下,使用它的构造函数将数据传递到第二页会容易得多
  • 有没有一种方法可以创建第二页并使其工作而无需通过第二页构造函数传递数据?

标签: c# .net xamarin xamarin.forms


【解决方案1】:

您必须在发送之前订阅。消息没有排队,它们会立即传递然后消失。通过构造函数传递数据会容易得多,但如果你坚持使用MessagingCenter

  1. 创建页面

    var page = new FirstPage();
    
  2. 订阅消息

    您已经在 FirstPage 构造函数中这样做了

  3. 发送消息

     MessagingCenter.Send<Page, string>(this, "Hi", "Data Sent");
    
  4. 导航到页面

     await Navigation.PushAsync(page);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多