This is my C# code, now it’s showing data in console.
class PlaceViewModel
{
public List<Vantaa.IntroPage.Place> Places;
}
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObject
{
public List<Place> Places { get; set; }
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
}
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var book in rootObject.Places)
{
System.Diagnostics.Debug.WriteLine(book.id);
}
this.DataContext = new PlaceViewModel
{
Places = rootObject.Places
};
}
What should I do with xaml file in order to show the data in textblock ?
This is my current xaml code. It’s surely not working. I really have no idea.
<ListBox ItemsSource="{Binding Places}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=id}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Your class-code looks good so now it’s just a matter of binding the results to the view. You are returning a list of objects so you should use a control that supports showing multiple items. Of course you could concatenate all the id’s of the books to one string and show it in a label. But this is not how it’s done. What you should do is add a ListBox control to the XAML and create a DataTemplate inside it. This way you set the way items will be displayed.
Create a class that will be the ViewModel for your XAML-page. This class will have a property ‘Places’ (type:
List<Place>). In the OnNavigatedTo-event when getting all the data is done, fill the ViewModel and bind and bind it to the DataContext of the XAML:This way you can grab all the objects from the ViewModel in your XAML:
Edit:
Here’s a working example:
XAML:
Place.cs:
MainViewModel.cs:
Sample repository (you should have your own):
MainWindow.xaml.cs: