使用 Messaging Center 将数据从一个页面传递到另一个页面

Pass Data from One Page to the other Page using Messaging Center

我正在尝试使用 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;
            });
        }
    }

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

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

  1. 创建页面

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

    您已经在 FirstPage 构造函数中执行此操作

  3. 发送消息

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

     await Navigation.PushAsync(page);