Search code examples
c#androidlistviewxamarinmvvmcross

Mvvmcross MvxListView item access viewmodel


I have a viewmodel with a list of a custom class. This list is displayed in my ui using a MvxListView. I can easly access the properties of the customs class, but what I need right now is a way to acces the viewmodel from them item template without modifying the class:

The class:

public class MyDataClass
{
    public string Name {get; set;};
}

The viewmodel:

public class MyViewModel : MvxViewModel
{
    //...
    private string _sample;
    public string Sample
    { 
        get { return this._sample; }
        private set { this.SetProperty(ref this._sample, value); }
    }

    private List<MyDataClass> _dataList;
    public List<MyDataClass> DataList
    { 
        get { return this._dataList; }
        private set { this.SetProperty(ref this._dataList, value); }
    } 
}

The MvxListView inside the view View:

<Mvx.MvxListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/testListView"
    local:MvxBind="ItemsSource DataList"
    local:MvxItemTemplate="@layout/data_item" />

And finally, the data_item:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceLarge"
    local:MvxBind="Text Name + ???.Sample"
    android:textColor="@color/primary"
    android:gravity="right|center_vertical"
    android:paddingEnd="5dp" />

The thing I need to get is ???.Sample, which should be the MyViewModel.Sample - but I don't know how to get it!

Note: I can not modify the MyDataClass to add the ViewModel as a property, this one has to stay unchanged. The Viewmodel itself and the views can be modified without a problem, to solve this.


Solution

  • Write a new class which wraps the MyDataClass class and add the new property which returns the concatenated property that the view needs. In the Sample setter loop over the list and update the new property.