[英]binding itemsource of listview from viewmodel
我的ListView保持为空。 我想念什么?
几乎全部编辑:我在模型中创建了JSON类。 我认为我的JSON有点错误。
我希望使用MVVM将存储在我的Web服务器上的json文件解析为列表视图。 现在,只有我手动输入的两个项目。
我真的很感谢您的帮助。
视图模型:
using KD_CHKLST.Models;
using KD_CHKLST.Utils;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
namespace KD_CHKLST.ViewModels
{
public class AbfahrtskontrolleViewModel : INotifyPropertyChanged
{
private ObservableCollection<Abfahrtskontrolle> items;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Abfahrtskontrolle> Items
{
get { return items; }
set
{
items = value;
}
}
public AbfahrtskontrolleViewModel()
{
Items = new ObservableCollection<Abfahrtskontrolle>() {
new Abfahrtskontrolle()
{
text = "Frage 1",
description = "Description 1"
},
new Abfahrtskontrolle()
{
text = "Frage 2",
description = "Description 2"
},
};
MyHTTP.GetAllNewsAsync(list =>
{
foreach (Abfahrtskontrolle item in list)
{
Items.Add(item);
}
});
}
}
}
模型:
using System.Collections.Generic;
namespace KD_CHKLST.Models
{
public class Abfahrtskontrolle
{
// JSON - Abfahrtskontrollfragen
public class Frage
{
public string text { get; set; }
public string description { get; set; }
}
public class RootObject
{
public IEnumerable<Frage> frage { get; set; }
}
}
}
我的json文件:
{
"frage": [{
"text": "Frage 1",
"description": "Frage 1 Description"
},
{
"text": "Frage 2",
"description": "Frage 2 Description"
}
]
}
最后是我的http课:
using KD_CHKLST.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
namespace KD_CHKLST.Utils
{
public class MyHTTP
{
public static async Task GetAllNewsAsync(Action<IEnumerable<Abfahrtskontrolle>> action)
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://xxx.xxx.xxx.xxx/chklst.json");
Debug.WriteLine(response.Content.ToString());
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var list = JsonConvert.DeserializeObject<IEnumerable<Abfahrtskontrolle>>(await response.Content.ReadAsStringAsync());
Debug.WriteLine(" hier ist meine geparste Liste: " + list);
action(list);
}
}
}
}
必须更改我的模型,json并向我的Items添加propertychangedevent。 现在可以了!
我更改的型号:
namespace KD_CHKLST.Models
{
public class Abfahrtskontrolle
{
public int FrageID { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
}
我更改的ObservableCollection: Items
ViewModel中的ObservableCollection: Items
:
public ObservableCollection<Abfahrtskontrolle> Items
{
get { return items; }
set
{
items = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Items)));
}
}
现在可以使用,因为我编辑了JSON:
[
{
"FrageID": 0,
"Text": "text 1",
"Description": "description 1"
},
{
"FrageID": 1,
"Text": "text 2",
"Description": "description 2"
}
]
现在它正在工作,我终于设法通过MVVM将数据绑定到列表视图中。 谢谢您的支持。
-p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.