c# – 从Xamarin Forms中的ViewModel绑定MasterDetailPage

我正在尝试从viewmodel绑定我的masterdetailpage细节.但它不起作用.

这是我的代码:

<?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>

这是我的viewmodel中的代码

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

当我放这行代码时,它正在工作

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

代码背后,但我想从视图模型中实现它.

请帮忙.先感谢您

最佳答案 您需要在Master和详细信息上添加绑定上下文:

<?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>

要在ViewModel中更改您的详细信息页面,我使用:

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

我不确定这是否是这项工作的最佳方式,MVVM和MasterDetail文档需要澄清.

不要忘记绑定上下文项需要实现INotifyPropertyChanged才能工作.

希望这有帮助.

点赞