Search code examples
xamarinandroid-recyclerviewmvvmcross

MvvmCross 6 RecyclerView multiple buttons item binding


I'm really new in Xamarin & more in MvvmCross. For the moment, I succeeded doing some basic stuff.

But now, I'm facing a simple problem (for me). I got an MvxRecyclerView. Each of its items has 2 buttons. How can I bind them?


Solution

  • Given your ViewModels:

    public class MyViewModel : MvxViewModel
    {
        public MyViewModel()
        {
            this.MyItems.Add(new MyItemViewModel());
            this.MyItems.Add(new MyItemViewModel());
        }
    
        public ObservableCollection<MyItemViewModel> MyItems { get; set; } = new ObservableCollection<MyItemViewModel>();
    }
    
    public class MyItemViewModel : MvxNotifyPropertyChanged
    {
         public MyItemViewModel()
         {
              // Initialize your commands
         }
    
         public ICommand MyCommand1 { get; set; }
    
         public ICommand MyCommand2 { get; set; }
    }
    

    In your view:

    <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="match_parent"
        android:layout_height="match_parent">
        <mvvmcross.droid.support.v7.recyclerview.MvxRecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            local:MvxItemTemplate="@layout/item_test"
            local:MvxBind="ItemsSource MyItems" />
    </LinearLayout>
    

    In your item view item_test.axml:

    <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="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="My button 1"
            local:MvxBind="Click MyCommand1" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="My button 2"
            local:MvxBind="Click MyCommand2" />
    </LinearLayout>
    

    HIH