Share Context on Xamarin Forms Xaml MasterDetailPage

466 Views Asked by At

I managed to make a MasterDetail Page on Xamarin Forms Xaml that works ok. My MasterDetailPage code is:

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage  xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:XXX.ViewModel"
             xmlns:conv="clr-namespace:XXX.Converters"
             xmlns:local="clr-namespace:XXX;assembly=XXX"
             x:Class="XXX.MainPage"
             Title="XXX">
  <MasterDetailPage.Master>
    <local:MainMenu />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <ContentPage BindingContext="{StaticResource viewModel}" Title="XXX">
      //old MainPage Content
   </ContentPage>
 </MasterDetailPage.Detail>

The app works right with the ViewModel, it launches like the old MainPage, and if I swing from left it shows the detail.

The problem comes because I did all the changes to do a filter menu for a listview who is in the Detail Content, and I need to share the context beetwen the detail and the Master, in order that, when the user press a button in the Master, the list content of the Detail changes.

Also I need to know how to open/close the MasterPage programatically.

2

There are 2 best solutions below

0
On BEST ANSWER

Ok, I found it here gaogang-athena Github

Just need to remove BindingContext from ContentPages and add:

<MasterDetailPage.BindingContext>
    <vm:MainViewModel />
  </MasterDetailPage.BindingContext>

To close or open it I used IsPresented, so at the end my code looks like:

  <?xml version="1.0" encoding="utf-8" ?>
  <MasterDetailPage  xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:XXX.ViewModel"
             xmlns:conv="clr-namespace:XXX.Converters"
             xmlns:local="clr-namespace:XXX;assembly=XXX"
             x:Class="XXX.MainPage"
             IsPresented="{Binding MasterIsPresented}"
             Title="XXX">
  <MasterDetailPage.BindingContext>
    <vm:MainViewModel />
  </MasterDetailPage.BindingContext>

  <MasterDetailPage.Master >
    <local:MainMenu/>
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <ContentPage  Title="XXX">
  ...
1
On

If you want to open / close MasterPage use this:

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

        void OnButtonClick(object sender, EventArgs e)
        {
            // hide master page
            this.IsPresented = false;
            // show master page
            this.IsPresented = true;
        }
    }