我是C#和XAML的新手,正在开发一个简单的天气应用程序,可让您搜索城市和州,并返回格式化的10天预测列表 .
我在使用ListView显示从Wunderground Weather API检索的数据时遇到问题 . 这是我正在使用的JSON,example.
My problem :在从Wunderground API获取结果后,如何通过XAML中的模板运行所有列表项,以显示项属性'(icon_url,title,fcttext)?
这是我的模型:
public class ForecastList
{
public class Forecastday
{
public string icon_url { get; set; }
public string title { get; set; }
public string fcttext { get; set; }
}
public class TxtForecast
{
public List forecastday { get; set; }
}
public class Forecast
{
public TxtForecast txt_forecast { get; set; }
}
public class RootObject
{
public Forecast forecast { get; set; }
}
}
XAML:
<Stack Layout Padding="30"> <StackLayout Orientation="Horizontal"> <Entry HorizontalOptions="FillAndExpand" Placeholder="City" x:Name="City" /> <Entry Placeholder="2 letter state" x:Name="State" /> </StackLayout> <Button Text="Search" Clicked="OnClicked" /> <ListView ItemsSource="{Binding ListSource}"> <ListView.ItemTemplate> <DataTemplate> <Label Text="{Binding Title}" /> <Label Text="{Binding FctText}" /> <Image Source="{Binding IconUrl}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout>
而ViewModel:
public class MainPageViewModel
{
public async Task GetWeatherAsync(string url)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
var response = await client.GetAsync(client.BaseAddress);
response.EnsureSuccessStatusCode();
var JsonResult = response.Content.ReadAsStringAsync().Result;
var weather = JsonConvert.DeserializeObject(JsonResult);
SetList(weather);
}
public List ListSource { get; set; }
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
private string _fctText;
public string FctText
{
get
{
return _fctText;
}
set
{
_fctText = value;
}
}
private string _iconUrl;
public string IconUrl
{
get
{
return _iconUrl;
}
set
{
_iconUrl = value;
}
}
private void SetList(ForecastList.RootObject weather)
{
ListView listView = new ListView();
var forecastList = weather.forecast.txt_forecast.forecastday;
List listSource = new List(forecastList);
ListSource = listSource;
listView.ItemsSource = ListSource;
}
}
干杯!
1 回答
您需要使用Dto将服务器数据转换为普通表单
例如 :
这是我的Dto
像这样从服务器获取数据
最后将myDto转换为我想要的原始格式
以下链接,清晰描述https://www.codeproject.com/Articles/36781/Serialization-and-Deserialization-in-ASP-NET-with