如何将参数从母版页传递到所有页面的xamarin表单

时间:2018-05-27 10:15:42

标签: c# xamarin xamarin.forms

点击按钮后出现Masterpage。

这是我的代码。

App.cs

public App()
 {
   // The root page of your application
   MainPage = new NavigationPage(new Login());
 }

Login.cs

public void button(object sender, EventArgs e)
 {
   MasterDetailPage fpm = new MasterDetailPage();
   fpm.Master = new MasterPage(**test.Text**) { Title = "Main Page" }; // You have to create a Master ContentPage()
   fpm.Detail = new NavigationPage(new PageOne()); // You have to create a Detail ContenPage()
   Application.Current.MainPage = fpm;
 }

从登录页面我将参数传递给母版页(即) test.text ,我想将此参数传递给Mastepage中的所有页面,但我不知道该怎么做

MasterPage.cs

public MasterPage(string id)
 {
   InitializeComponent();
   BindingContext = new MasterViewModel();
 }

MasterViewModel.cs

public ICommand NavigationCommand
 {
  get
   {
     return new Command((value) =>
      {
        // COMMENT: This is just quick demo code. Please don't put this in a production app.
        var mdp = (Application.Current.MainPage as MasterDetailPage);
        var navPage = mdp.Detail as NavigationPage;
        // Hide the Master page
        mdp.IsPresented = false;
         switch(value)
          {
            case "1":
                    navPage.PushAsync(new PageOne());
                    break;
            case "2":
                    navPage.PushAsync(new PageTwo());
                    break;
          }
      });
   }
}

所以基本上我需要的是登录后我想将id传递给Masterpage,因此Masterpage中的所有页面都可以获得该id,并且基于id我可以在这个项目上工作。

1 个答案:

答案 0 :(得分:0)

您可以使用messaging center

你这样发送:

MessagingCenter.Send<MainPage> (this, "Hi");

你这样收到:

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});

不要忘记取消订阅:

MessagingCenter.Unsubscribe<MainPage> (this, "Hi");