简体   繁体   中英

Bind MasterDetailPage from ViewModel in Xamarin Forms

I'm trying to bind my masterdetailpage detail from viewmodel. But it doesn't work.

Here's my code in view:

<?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:local="clr-namespace:MasterDetailsSamp1"
         x:Class="MasterDetailsSamp1.MainPage"
         xmlns:vm="clr-namespace:MasterDetailsSamp1.ViewModels">
<MasterDetailPage.BindingContext>
    <vm:MasterDetailsViewModel/>
</MasterDetailPage.BindingContext>

<MasterDetailPage.Master>
    <ContentPage Title="Menu">
        <StackLayout>

        </StackLayout>
    </ContentPage>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <NavigationPage>

    </NavigationPage>
</MasterDetailPage.Detail>

Here's my code in my viewmodel

public MasterDetailsViewModel()
{
    MasterDetailPage masterDetailPage = new MasterDetailPage
    {
        Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(HomePage)))
    };
}

It's working when I put this line of code

Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(HomePage)))

behind the code, but I want to achieve it from view model.

Please help. Thank you in advance

You need to add binding context on your Master and detail like that :

<?xml version="1.0" encoding="UTF-8" ?> 
<MasterDetailPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    x:Class="MasterDetailExample.Main"
    Title="Master Detail Example">

    <MasterDetailPage.Master>
      <ContentPage Padding="5, 25"  BindingContext="{Binding Menu}" Title="Master">
          <StackLayout Orientation="Vertical">
              <Label Text="Master" HorizontalOptions="Center" />
              <Label Text="{Binding Subtitle}" HorizontalOptions="Center" />
          </StackLayout>
        </ContentPage>

    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <ContentPage>
        </ContentPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>

To change your detail page in ViewModel I use this :

(Application.Current.MainPage as MasterDetailPage).Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(YOURDETAILPAGE)));

I'm not sure if it's the best way to this job, MVVM and MasterDetail documentions need to be clarify.

Don't forget that your binding context item need to implement INotifyPropertyChanged to work.

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM