MvxListView create binding for template layout from code

前端 未结 1 638
余生分开走
余生分开走 2020-12-05 20:55

Lets say I have a simple Layout with a MvxListView:




        
相关标签:
1条回答
  • 2020-12-05 21:32

    To do the bindings in code it's probably best to:

    1. implement a custom MvxListViewItem
    2. implement a custom MvxAdapter to return the custom list view item
    3. implement a custom MvxListView to use the custom MvxAdapter

    Not tested, but the code for this is roughly:

    1. implement a custom MvxListViewItem

    public class CustomListItemView
        : MvxListItemView
    {
        public MvxListItemView(Context context,
                               IMvxLayoutInflater layoutInflater,
                               object dataContext,
                               int templateId)
            : base(context, layoutInflater, dataContext, templateId)
        {
            var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
            var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
            set.Bind(control).To(vm => vm.Title);
            set.Apply();
        }
    }
    

    2. Create a custom MvxAdapter

    In this override CreateBindableView

    public class CustomAdapter
        : MvxAdapter
    {
        public CustomAdapter(Context context)
            : base(context)
        {
        }
    
        protected override IMvxListItemView CreateBindableView(object dataContext, int templateId)
        {
            return new CustomListItemView(_context, _bindingContext.LayoutInflater, dataContext, templateId);
        }
    }
    

    original: https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Droid/Views/MvxAdapter.cs#L298

    3. implement a custom MvxListView to use the adapter

    This should be as simple as:

    public class CustomListView
        : MvxListView
    {
        public CustomListView(Context context, IAttributeSet attrs)
            : base(context, attrs, new CustomAdapter(context))
        {
        }
    }
    

    As long as this is in your main UI assembly, this should be useable in your axml as:

    <CustomListView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        local:MvxBind="ItemsSource AutoListItems; ItemClick AutoListItemClicked"
        local:MvxItemTemplate="@layout/vbmvxautoviewlistitem" />
    

    If CustomListView is not in your main UI assembly, then there are some tricks to get MvvmCross to pick it up during your Setup - see Providing Custom Android View Assemblies in https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup#wiki-providing-custom-views-android


    The above is the best way to do this (IMO) - but if you wanted to, then you could do it in less code by just applying the bindings inside the custom adapter and by setting that adapter in OnCreate in your Activity

    0 讨论(0)
提交回复
热议问题