【问题标题】:Bind MasterDetailPage from ViewModel in Xamarin Forms在 Xamarin 表单中从 ViewModel 绑定 MasterDetailPage
【发布时间】:2018-03-13 17:36:28
【问题描述】:

我正在尝试从 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>

这是我的视图模型中的代码

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

当我输入这行代码时它正在工作

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

在代码后面,但我想从视图模型中实现它。

请帮忙。提前谢谢你

【问题讨论】:

    标签: c# xaml xamarin mvvm xamarin.forms


    【解决方案1】:

    你需要在你的 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 才能工作。

    希望对您有所帮助。

    【讨论】:

    • 是的,我知道。我的意思是,现在应该从 ViewModel 调用,在 MasterDetailPage.Detail 中创建一个内容页面布局 :)
    • 加起来,我的 ViewModel 中还有 INotifyPropertyChanged,一切正常。问题是,当我将这段代码“Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(HomePage)))”放在我的视图模型中时,它不起作用。但是如果你把它放在页面的 InitializeComponent() 之后的代码后面,它就可以工作了。
    • 我遇到了一个错误。它说“System.Reflection.TargetInvocationException:”
    猜你喜欢
    • 2021-10-20
    • 2018-03-01
    • 2017-01-24
    • 2017-01-15
    • 2018-08-16
    • 1970-01-01
    • 2015-04-21
    • 2018-04-02
    相关资源
    最近更新 更多