List <object>中嵌套对象的ListView绑定属性

时间:2017-10-05 10:53:15

标签: c# xamarin.forms

我试图绑定一个名为&#34; Name&#34;的字符串属性。来自列表&lt; T>由我在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; }
}

在我的网页中,我设置ListView.ItemSource来自调用异步,这是一个List<MyObject>

 var itemSource = listOfMyObject;

我有一个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");
    }
}

所以一切都正确绑定,除了我的ListView中没有显示的Object.Name

我知道它不起作用,因为我的对象是一个List&lt; T>并且没有Name属性。好吧,但我怎样才能实现我的目标呢?我不想只为一个标签使用嵌套的listView 我已经看到我可以得到一个平面的数据列表,例如: listOfMyObject.SelectMany(obj => obj.Objects)

但不知道该怎么做。 那么如何在MyObject列表中绑定Object的属性呢?

由于

1 个答案:

答案 0 :(得分:1)

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
}