如何在xamrain c中获取一个标签中的符号和另一个标签的价格#我需要帮助的是如何在列表视图中显示所有不同硬币的符号和价格。你可以在GetPrice下的链接中看到不同的符号和不同的价格。我只想把它们分组,然后在列表视图中把它们分开。请帮帮我。
这是我的主页.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Crypto_Portfolio.MainPage">
<StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="Start">
<ListView x:Name="priceList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding symbol}" />
<Label Text="{Binding price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="End">
<Button Clicked="priceClick" Text="Fetch Price" HorizontalOptions="CenterAndExpand" VerticalOptions="End"/>
</StackLayout>
</StackLayout>
</ContentPage>
这是我的主页.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace Crypto_Portfolio
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
GetPrice();
}
public class Crypto
{
public string symbol { get; set; }
public string price { get; set; }
}
private async void GetPrice()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("https://api.binance.com/api/v3/ticker/price");
var cryptoconverted = JsonConvert.DeserializeObject<List<Crypto>>(response);
priceList.ItemsSource = cryptoconverted;
}
void priceClick(object sender, EventArgs e)
{
GetPrice();
}
}
}
首先,您需要将webservice中的json反序列化到C#类中。您可以使用json2csharp.com来访问此
public class Stock
{
public string symbol { get; set; }
public string price { get; set; }
}
然后在你的GetPrice
方法
var response = await client.GetStringAsync("https://api.binance.com/api/v3/ticker/price");
var stocks = JsonConvert.DeserializeObject<List<Stock>>(response);
接下来,将ListView
添加到XAML
<ListView x:Name="stockList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding symbol}" />
<Label Text="{Binding price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
最后,将您的数据分配给GetPrice
中的ListView
stockList.ItemsSource = stocks