绑定ViewModel以查看DataContext

时间:2017-04-26 23:06:33

标签: xamarin.android mvvmcross

我在Android应用程序上使用MvvmCross。我有1个全局ViewModel和2个子ViewModel(都来自MvxViewModel):

public class GlobalViewModel : MvxViewModel
{
    private SubViewModel1 _subViewModel1;
    public SubViewModel1 SubViewModel1
    {
        get { return _subViewModel1; }
        set { _subViewModel = value; RaisePropertyChanged(() => SubViewModel); }
    }

    private SubViewModel2 _subViewModel2;
    public SubViewModel2 SubViewModel
    {
        get { return _subViewModel2; }
        set { _subViewModel2 = value; RaisePropertyChanged(() => SubViewModel); }
    }
}

在我的xml中,我想将2个子ViewModels绑定到源自MvxLinearLayout的自定义视图的数据上下文中:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <MyMvxLinearLayout1
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        local:MvxBind="SubViewModel1" />
    <MyMvxLinearLayout2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:gravity="center"
        local:MvxBind="SubViewModel2" />
</FrameLayout>

MyMvxLinearLayout1MyMvxLinearLayout2内的绑定无效。有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

做了一些研究后,我发现了它。在我的自定义视图中,我添加了以下字段/属性:

private readonly IMvxAndroidBindingContext _bindingContext;

[MvxSetToNullAfterBinding]
public object DataContext
{
    get { return _bindingContext.DataContext; }
    set
    {
        _bindingContext.DataContext = value;
    }
}

然后在构造函数中:

_bindingContext = new MvxAndroidBindingContext(context, (IMvxLayoutInflaterHolder)context);
var myView = _bindingContext.BindingInflate(Resource.Layout.my_view, null, true); // myView will now have all the proper binding setup, just add it to your layout now

在.xml中:

<MyMvxLinearLayout1
android:layout_width="match_parent"
android:layout_height="match_parent"    
local:MvxBind="DataContext SubViewModel1" />