我有以下JSON网址。我正在尝试使用子代码hair []和math []填充我的列表视图,然后从JSON URL获取它们。
以下是网址http://pastebin.com/raw.php?i=2fzqLYXj
阵列内部"学生"有一个名为" Properties"和另一个子阵列"属性"叫"成绩"。 "头发"在里面"属性"和"数学"在里面"成绩"。
这是我的WebService类
public class WebService
{
public WebService ()
{
}
public async Task<Rootobject> GetStudentInfoAsync (string apiurl) {
var client = new HttpClient ();
var response = await client.GetStringAsync(string.Format(apiurl));
return JsonConvert.DeserializeObject<Rootobject>(response.ToString());
}
}
这是我的视图模型
public class Property
{
public int iq { get; set; }
public string hair { get; set; }
public string glasses { get; set; }
public Grade[] Grades { get; set; }
}
public class StudentInfo
{
public string name { get; set; }
public string lastname { get; set; }
public Property[] Properties { get; set; }
public string StudentName {
get{ return String.Format ("{0}", name); }
}
//I am accessing the JSON sub arrays with the following to get the "hair" and "math" properties.
public string[] HairColors
{
get
{
return (Properties ?? Enumerable.Empty<Property>()).Select(p => p.hair).ToArray();
}
}
public string[] MathGrades
{
get
{
return (Properties ?? Enumerable.Empty<Property>()).SelectMany(p => p.Grades ?? Enumerable.Empty<Grade>()).Select(g => g.Math).ToArray();
}
}
}
public class Rootobject
{
public StudentInfo[] students { get; set; }
}
}
以下是我使用学生姓名填充列表视图的方法。注意&#34; StudentName&#34;不是在一个子阵列中。
var sv = new WebService();
var es = await sv.GetStudentInfoAsync(apiurl);
Xamarin.Forms.Device.BeginInvokeOnMainThread( () => {
listView.ItemsSource = es.students;
});
var cell = new DataTemplate (typeof(TextCell));
listView.ItemTemplate = cell;
listView.ItemTemplate.SetBinding(TextCell.TextProperty, "StudentName");
但我需要使用HairColors和MathGrades填充我的列表视图,如下所示,但以下代码不起作用。
var sv = new WebService();
var es = await sv.GetStudentInfoAsync(apiurl);
Xamarin.Forms.Device.BeginInvokeOnMainThread( () => {
listView.ItemsSource = es.students;
});
var cell = new DataTemplate (typeof(TextCell));
listView.ItemTemplate = cell;
listView.ItemTemplate.SetBinding(TextCell.TextProperty, "HairColors");
listView.ItemTemplate.SetBinding (TextCell.DetailProperty, "MathGrades");
这段代码有什么用?我如何使它工作?
答案 0 :(得分:0)
您可以为此制作自定义转换器:
public class HairColorsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var hairColors = (string[])value;
return string.Join(", ", hairColors);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后绑定它:
SetBinding(TextCell.TextProperty, "HairColors", BindingMode.Default, new HairColorsConverter());