MohamedAbbas
MohamedAbbas

Reputation: 1161

Data binding in ListBox on Windows Phone 8

I'm new to Windows Phone 8. I have a list of data from a server in this form:

RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);

  mylist.ItemsSource = json.friends;
public class Friend
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string place { get; set; }
    public string going { get; set; }
    public string thumbnail { get; set; }
}

    public class RootObject
    {
        public List<Friend> friends { get; set; }
    }

I want to display that data in a ListBox in the UI:

  <ListBox x:Name="mylist" Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel Margin="10,0,10,8">
                        <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding last_name }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding place }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding going }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding thumbnail }" TextWrapping="Wrap" FontSize="18" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

that is a working version

Upvotes: 0

Views: 3848

Answers (1)

Johan Falk
Johan Falk

Reputation: 4359

The ItemsSource on the ListBox should be bound to friends, like this:

<ListBox ItemsSource="{Binding friends}"  Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
    <ListBox.ItemTemplate>
        <DataTemplate >
            <StackPanel Margin="10,0,10,8">
                <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
                <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="24" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And also if you haven't done it already, you need to set the DataContext for the page after you downloaded the data, like this (assuming you do the downloading in the code-behind file of a page, e.g. MainPage.xaml.cs):

RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
this.DataContext = json;

Upvotes: 1

Related Questions