[英]Populate WPF DataGrid With JSON Data in C# using RestSharp
I would tell you I am relatively new to all of this, but it will probably be obvious shortly. 我会告诉您,我在所有这些方面都比较陌生,但不久后可能会很明显。 I have been researching for two days without any luck in finding my specific question answered so here is what I am trying to do: 我已经进行了两天的研究,没有运气能找到我所回答的具体问题,所以这是我想做的事情:
In the MainWindow code behind of a WPF app I have this class: 在WPF应用程序后面的MainWindow代码中,我有这个类:
public class LocaleInfo
{
public string id { get; set; }
public string category { get; set; }
public bool jobSite { get; set; }
public bool singleJob { get; set; }
public bool useMasterPack { get; set; }
public string maxAllowed { get; set; }
}
Which I add a list to in order to handle JSON data coming from a web service formatted as an array. 我添加了一个列表,以处理来自格式化为数组的Web服务的JSON数据。 (Comments added to help you understand my line of thinking and maybe shed light on why I built each line like I did - hope it helps!) (添加的注释可帮助您理解我的思路,也许可以阐明为什么我像以前那样建立每条思路-希望它能有所帮助!)
public List<LocaleInfo> LocaleList;
I then have the following code to get the JSON data: 然后,我有以下代码来获取JSON数据:
var client = new RestClient("https://webservice info"); // Create Rest Client
var request = new RestRequest(Method.GET); //Create Rest Request
request.RequestFormat = RestSharp.DataFormat.Json; // Request JSON to ensure accuracy
request.AddHeader("Authorization", "tokenxxx"); // Add header item Authorization and Token
var response = client.Execute(request); // Execute the Request
JsonDeserializer deserial = new JsonDeserializer(); // Create JSON Deserializer object
LocaleList = deserial.Deserialize<List<LocaleInfo>>(response); // Deserialize JSON Receieved from API/WEbservice into List<class>
Int32 totalCount = LocaleList.Count; // Create variable and get total record count
txtCount.Text = totalCount.ToString(); // Show record count
I believe it populates the list as I get a proper count. 我相信只要我有适当的计数,它就会填充列表。
On the MainWindow.xaml I have placed a DataGrid with 6 columns with headers. 在MainWindow.xaml上,我放置了一个带有6列带有标题的DataGrid。 What I cannot seem to find or figure out is how to link or iterate through the list to add the data into the DataGrid. 我似乎找不到或弄清楚的是如何链接或遍历列表以将数据添加到DataGrid中。
Someday I will look back on this post and probably shake my head, but this is where I am at and I could really use some help. 总有一天,我会回头看这篇文章,也许会摇头,但这就是我的位置,我真的可以使用一些帮助。
Thanks so much in advance! 非常感谢!
Add this in your MainWindow's Constructor : 将其添加到MainWindow的Constructor中:
DataContext = this;
then use ObservableCollection instead of List : 然后使用ObservableCollection而不是List:
Public ObservableCollection<LocalInfo> LocalList{get; set;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.