Drake
Drake

Reputation: 2703

Bind ViewModel to View DataContext

I am using MvvmCross on my Android application. I have 1 global ViewModel with 2 sub ViewModels (both derive from 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); }
    }
}

In my xml, I want to bind the 2 sub ViewModels to the data context of my custom views that derive from 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>

But the binding inside MyMvxLinearLayout1 and MyMvxLinearLayout2 aren't working. Is there something I'm missing?

Upvotes: 0

Views: 894

Answers (1)

Drake
Drake

Reputation: 2703

After doing some research, I figured it out. In my custom views, I add these fields/properties:

private readonly IMvxAndroidBindingContext _bindingContext;

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

And then in the constructor:

_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

And in the .xml:

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

Upvotes: 1

Related Questions