【发布时间】:2020-03-21 14:17:16
【问题描述】:
我可以使用数组来显示从 Web 服务获得的数据,并在列表视图中显示它们吗?
这是我的代码的 sn-p:
class WSResult2
{
public string url { get; set; }
public string equipment { get; set; }
public string serial { get; set; }
}
class WSResultList
{
public List<WSResult2> items { get; set; }
}
Page4.xaml.cs:
private async Task wsvarAsync(Result result)
{
WSClient client = new WSClient();
string wUrl = "--Here is the url of the web service--" + result.Text + "&option=2";
var resultws = await client.Get<WSResultList>(wUrl);
if (resultws != null)
{ //I want to know how to use an array here to get the complete list of each of the items captured by the web service.
lblEquipment.Text = resultws.items[0].equipment;
lblSerial.Text = resultws.items[0].serial;
lblurl.Text = resultws.items[0].url;
}
}
Page4.xaml:
<ContentPage.Content>
<StackLayout Padding="20">
<StackLayout HorizontalOptions="Center">
<Button x:Name="btnScan" Text="Read code" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand" BackgroundColor="LightBlue" TextColor="White" FontSize="Medium" CornerRadius="25" Clicked="btnScan_Clicked"/>
</StackLayout>
<Label x:Name="lblInfo" />
<Label Text="Equipment: " TextColor="Red"/>
<Label x:Name="lblEquipment" />
<Label Text="Serial: " TextColor="Red"/>
<Label x:Name="lblSerial" />
<!-- I want to know how to use a Binding to show all the data captured from the web service. -->
<Label IsVisible="False" Text="Report: " TextColor="Red"/>
<Label IsVisible="False" x:Name="lblurl" />
<Button x:Name="btnUrl" Text="See report" Clicked="OnButtonClicked" CornerRadius="25" HorizontalOptions="Center" TextColor="White" FontSize="Medium" BackgroundColor="Red"/>
</StackLayout>
</ContentPage.Content>
WSClient.cs 是反序列化 JSON 的客户端:
class WSClient
{
public async Task<T> Get<T>(string url)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
public async Task<T> Post<T>(string pUrl, T pData)
{
var wJsonData = JsonConvert.SerializeObject(pData);
var wData = new StringContent(wJsonData, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var wResponse = await client.PostAsync(pUrl, wData);
var json = await wResponse.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
}
【问题讨论】:
-
你想在 ListView 中显示数组数据吗?
-
@Jhon117 你能不能试着用
List<WSResult2> items = await client.Get<List<WSResult2>>(wUrl);替换你的代码,然后你会得到List项,你可以用ListView显示数据。
标签: c# xaml xamarin.forms