MvvmCross创建自定义绑定到LinearLayout

时间:2018-06-15 16:13:35

标签: xamarin mvvmcross

我正在尝试创建一个自定义绑定到LinearLayout,以允许我动态创建一个视图并将其作为子项绑定到LinearLayout。对于熟悉WPF的人来说,这类似于ContentControl或从ContentControl派生的任何WPF控件提供的功能。基本上,您可以创建动态内容并绑定到ContentControl的Content属性。

以下是我对自定义绑定的看法:

  public class MvxLinearLayoutContentTargetBinding : MvxPropertyInfoTargetBinding<LinearLayout>
    {
        public MvxLinearLayoutContentTargetBinding(object target, PropertyInfo targetPropertyInfo) : base(target, targetPropertyInfo)
        {
        }

        protected override void SetValueImpl(object target, object value)
        {
            base.SetValueImpl(target, value);
            var view = target as LinearLayout;

            if (view == null) return;

            view.AddView((View)value);
        }

        public override Type TargetType
        {
            get { return typeof(LinearLayout); }
        }
    }

以下是我尝试在布局中使用此新绑定的方法:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="3dp"
    android:paddingTop="3dp"
    android:paddingLeft="5dp">
  <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="3dp"
        android:paddingTop="3dp"
        android:paddingLeft="0dp"
        local:MvxBind="Content CustomView">

    </LinearLayout>  

</LinearLayout>

我的任何ViewModel都是这样的:

  public class CustomViewModel : MvxViewModel
    {
        public object CustomView { get; set; }
    }

自定义绑定也已在Setup.cs中注册,如下所示:

  protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
        {           
            registry.RegisterPropertyInfoBindingFactory(
                typeof(MvxLinearLayoutContentTargetBinding),
                typeof(LinearLayout), "Content");

            base.FillTargetFactories(registry);
        }

然而,有了这一切,我看不出自己的观点。

1 个答案:

答案 0 :(得分:1)

MvvmCross已经支持这个的原始版本。虽然没有DataTemplateSelector。

您可以将ViewModel的集合绑定到MvxLinearLayout.ItemsSource。您还需要记住设置ItemTemplateId

<MvxLinearLayout
    ...
    local:MvxItemTemplateId="@layout/layout_to_repeat"
    local:MvxBind="ItemsSource ViewModelCollection"
    />

然而,这是非常低效的,因为它不回收视图等。因此,如果您需要一个支持DataTemplateSelector的变体,那么请改用MvxRecyclerView

相关问题