【问题标题】:MvvmCross creating custom binding to LinearLayoutMvvmCross 创建自定义绑定到 LinearLayout
【发布时间】:2018-06-15 16:13:35
【问题描述】:

我正在尝试创建与 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);
        }

然而,这一切都已经到位,我看不到自己的观点。

【问题讨论】:

    标签: xamarin mvvmcross


    【解决方案1】:

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

    您可以将一组 ViewModel 绑定到 MvxLinearLayout.ItemsSource。你还需要记住设置一个ItemTemplateId

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多