Umar3x
Umar3x

Reputation: 1084

ListView binding property of nested object in List<Object>

I'm trying to bind a string property called "Name" from a List < T > holded by the object I'm binding to in a listView.

public class MyObject 
{
    public List<Object> Objects{ get; set; }
    public string Description {get; set; }
    public string StartDate {get; set; }
    public string EndDate {get ;set; }
    public string Type {get; set; }

    public MyObject()
    {
        Objects = new List<Object>();
    }
}

public class Object
{
    public string Name { get; set; }
    public int? Id { get; set; }
    public int? Order { get; set; }
}

In my Page, I set ListView.ItemSource from call async which is a a List<MyObject>

 var itemSource = listOfMyObject;

I got a DataTemplate

public class Cell : ViewCell     
{
    private void SetBindings()
    {
        _objectLabel.SetBinding(Label.TextProperty, "Object.Name");
        _descriptionLabel.SetBinding(Label.TextProperty, "Description");
        _dateStartLabel.SetBinding(Label.TextProperty, "StartDate");
        _dateEndLabel.SetBinding(Label.TextProperty, "EndDate");
        _typeOfRequest.SetBinding(Label.TextProperty, "Type");
    }
}

So everything is bound correctly, except for Object.Name which does not display in my ListView.

I know it doesn't work because my Objects is a List< T > and does not have the Name property. Well, but how can I achieve what I want ? And I do not want to use nested listView just for one label.
I've seen that I can get a flat list of the data with something like : listOfMyObject.SelectMany(obj => obj.Objects)

but don't know what do of that. So how could I bind the property of the Object in the List of MyObject ?

Thanks

Upvotes: 0

Views: 684

Answers (1)

Alessandro Caliaro
Alessandro Caliaro

Reputation: 5768

public class ListToStringConverter : IValueConverter
{

    #region IValueConverter implementation

    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value!= null)  {
           List<Object> temp = (List<Object>)value;
           if(temp.Count == 0 )
                return "";

           string myString = "";
           foreach(Object obj in temp){
               myString += obj.Name + ",";
          }

          return myString;
        }
        return "";
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }

    #endregion
}

Upvotes: 1

Related Questions