Search code examples
xamarinmvvmcrossmvxlistview

MvvmCross MvxListView ItemClick Enabled Based on property


So I have a MvxListView

<Mvx.MvxListView
    android:id="@+id/receptionsListView"
    android:divider="@drawable/divider"
    android:scrollbars="vertical"
    android:choiceMode="singleChoice"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    local:MvxItemTemplate="@layout/item_supplier"
    local:MvxBind="ItemsSource ReceptionSuppliersList;  ItemClick SelectReceptionCommand;" />

I want to enabled/disabled some Items based on a value from model in the list. Something like

  local:MvxBind="ItemsSource ReceptionSuppliersList; ItemClick SelectReceptionCommand; Enabled ReceptionSuppliersList.IsValid" />

From what I've tested this just disabled all my list items because there is no such property ReceptionSuppliersList.IsValid ( it's ReceptionSuppliersList[i].IsValid ). How can I achive this.

I also tried to add the Enabled Property on item_supplier like this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="0dp"
    style="@style/ExtendProTheme.ReceptionItem"
    local:MvxBind="Enabled IsValid" >

But it still doesn't work.

Any ideas how can i disable some of the item from my list based on a property?

PS : My items look like this

public string Username { get; set; }

public string DeviceId { get; set; }

public bool IsValid { get; set; }

Solution

  • You could create a custom adapter to handle the enabling/disabling of list items. You would just need to cast the Adapters ItemsSource to your ViewModels ReceptionSuppliersList type in the IsEnabled override.

    public class CustomAdapter : MvxAdapter
    {
        public CustomAdapter(Context context) 
            : base(context)
        {
        }
    
        public CustomAdapter(Context context, IMvxAndroidBindingContext bindingContext) 
            : base(context, bindingContext)
        {
        }
    
        protected CustomAdapter(IntPtr javaReference, JniHandleOwnership transfer) :
            base(javaReference, transfer)
        {
        }
    
        public override bool IsEnabled(int position)
        {
            var items = ItemsSource as List<TestModel>;
            return items[position].IsValid;
        }
    }
    

    Assign adapter to your MvxListView:

    var receptionsListView = FindViewById<MvxListView>(Resource.Id.receptionsListView);
    receptionsListView.Adapter = new CustomAdapter(this, BindingContext as IMvxAndroidBindingContext);