I am new to C# and XAML and am working on a simple Weather App that lets you search for city and state and returns a formatted 10-day forecast list.
I'm having problems displaying data retrieved from the Wunderground Weather API using a ListView. This is the JSON I'm working with, example.
My problem: How do I run all List items through a template in XAML that displays the items properties' (icon_url, title, fcttext) after we get the results from the Wunderground API?
Here is my model:
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>
And the 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;
}
}
Cheers!
You need to convert server data to normal form using Dto's
for example :
This is my Dto
Getting data from server like this
and finally converting myDto to original format that i want to
below link with clear description https://www.codeproject.com/Articles/36781/Serialization-and-Deserialization-in-ASP-NET-with