【问题标题】:Bind ViewModel to View DataContext将 ViewModel 绑定到 View DataContext
【发布时间】:2017-04-26 23:06:33
【问题描述】:

我在我的 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 个子 ViewModel 绑定到从 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>

但是MyMvxLinearLayout1 和MyMvxLinearLayout2 内部的绑定不起作用。我有什么遗漏吗?

【问题讨论】:

  • 您的自定义 MvxLinearLayout 是否公开了您希望将子 ViewModel 绑定到的属性?您将需要一个属性来在您的控件中保存 ViewModel。
  • 这实际上不是我想要做的。我正在尝试绑定到视图的数据上下文。在 WPF 和 Window Phone 中,这是通过绑定到 DataContext 属性来完成的。

标签: xamarin.android mvvmcross


【解决方案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" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多