2017-04-26 108 views
0

我在我的Android應用程序上使用MvvmCross。我有1個與2周的ViewModels(從MvxViewModel都獲得)的全球視圖模型:將ViewModel綁定到View DataContext

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

請問您的自定義'MvxLinearLayout'公開一個屬性,你想要綁定你的子視圖模型?您將需要一個屬性來控制ViewModel。 – Plac3Hold3r

+0

這實際上不是我想要做的。我試圖綁定到視圖的數據上下文。在WPF和Window Phone中,這是通過綁定到'DataContext'屬性來完成的。 – Darius

回答

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" /> 
相關問題